Javascript 如何使用firebase cloud firestore为react中的复选框保留多个数据?

Javascript 如何使用firebase cloud firestore为react中的复选框保留多个数据?,javascript,reactjs,firebase,google-cloud-firestore,Javascript,Reactjs,Firebase,Google Cloud Firestore,我无法使用复选框存储数据的多个值。单击“提交”按钮后,值不会存储为数组。仅在单个字段中记录最新值。当我尝试在中写入行为[0]时,它似乎存储为firebase数据库中的behavoiur[]。如何在数组中正确存储数据 import React, { Component } from 'react'; import fire from '../config/Fire'; import { Link } from 'react-router-dom'; import Navigation from '

我无法使用复选框存储数据的多个值。单击“提交”按钮后,值不会存储为数组。仅在单个字段中记录最新值。当我尝试在
中写入
行为[0]
时,它似乎存储为firebase数据库中的
behavoiur[]
。如何在数组中正确存储数据

import React, { Component } from 'react';
import fire from '../config/Fire';
import { Link } from 'react-router-dom';
import Navigation from '../components/Navigation';

class CreateForm extends Component {

  constructor() {
    super();
    this.ref = fire.firestore().collection('form');
    this.state = {
      status: '',
      date: '',
      time: '',
      project: '',
      department: '',
      phone: '',
      detail: '',
      behaviour: [],
      tool: [],
      environment: [],
      action: '',
      photo: '',
      cases: ''
    };
  }

  handleChange(e) {
    // current array of options
    const options = this.state.options
    let index

    // check if the check box is checked or unchecked
    if (e.target.checked) {
      // add the numerical value of the checkbox to options array
      options.push(+e.target.value)
    } else {
      // or remove the value from the unchecked checkbox from the array
      index = options.indexOf(+e.target.value)
      options.splice(index, 1)
    }

    // update the state with the new array of options
    this.setState({ options: options })
  }

  onChange = (e) => {
    const state = this.state
    state[e.target.name] = e.target.value;
    this.setState(state);
  }

  onSubmit = (e) => {
    e.preventDefault();

    const { status, date, time, project, department, phone, detail, behaviour, tool, environment, action, photo, cases } = this.state;

    this.ref.add({
      status,
      date,
      time,
      project,
      department,
      phone,
      detail,
      behaviour,
      tool,
      environment,
      action,
      photo,
      cases
    }).then((docRef) => {
    this.setState({
      status: '',
      date: '',
      time: '',
      project: '',
      department: '',
      phone: '',
      detail: '',
      behaviour: [],
      tool: [],
      environment: [],
      action: '',
      photo: '',
      cases: ''
      });
      this.props.history.push("/form")
    })
    .catch((error) => {
      console.error("Error adding document: ", error);
    });
  }

  render() {
    const { status, date, time, project, department, phone, detail, behaviour, tool, environment, action, photo, cases } = this.state;
    return (
    <div>
    <Navigation />

      <div class="container">
        <div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">
            <p></p>
              ADD FORM
            </h3>
          </div>
          <div class="panel-body">
            <h4><Link to="/form" class="btn btn-primary">Cancel</Link></h4>
            <form onSubmit={this.onSubmit}>
              <div class="form-group">
                <label for="status">Status: &nbsp;</label>
                <input type="radio" name="status" value="Unsafe Act" onChange={this.onChange}/> Unsafe Act &nbsp;
                <input type="radio" name="status" value="Unsafe Condition" onChange={this.onChange}/> Unsafe Condition
              </div>
              <div class="form-group">
                <label for="date">Date: </label>
                <input type="date" class="form-control" name="date" value={date} onChange={this.onChange} placeholder="Select date" required/>
              </div>
              <div class="form-group">
                <label for="time">Time: </label>
                <input type="time" class="form-control" name="time" value={time} onChange={this.onChange} placeholder="Select time" required/>
              </div>
              <div class="form-group">
                <label for="project">Project: </label>
                <input type="text" class="form-control" name="project" value={project} onChange={this.onChange} placeholder="Select project" required/>
              </div>
              <div class="form-group">
                <label for="department">Department: </label>
                <input type="text" class="form-control" name="department" value={department} onChange={this.onChange} placeholder="Select department" required/>
              </div>
              <div class="form-group">
                <label for="phone">Phone number: </label>
                <input type="text" class="form-control" name="phone" value={phone} onChange={this.onChange} placeholder="Insert phone number" required/>
              </div>
              <div class="form-group">
                <label for="detail">Detail Description of Unsafe Act Unsafe Condition Observed : </label>
                <input type="text" class="form-control" name="detail" value={detail} onChange={this.onChange} placeholder="Insert details" required/>
              </div>
              <div class="form-group">
                <br></br>
                <label for="behaviour">People & At Risk Behaviours: </label><br></br>
                <input type="checkbox" name="behaviour" onChange={this.handleChange.bind(this)} value="Annoyance and horseplay in the workplace"/> Annoyance and horseplay in the workplace<br></br>
                <input type="checkbox" name="behaviour" onChange={this.handleChange.bind(this)} value="Removing safety guards from the workplace or equipment"/> Removing safety guards from the workplace or equipment<br></br>
                <input type="checkbox" name="behaviour" onChange={this.handleChange.bind(this)} value="Improper posture of task"/> Improper posture of task<br></br>
                <input type="checkbox" name="behaviour" onChange={this.handleChange.bind(this)} value="Risk of contact with electric  current/ hot surface/ hot water"/> Risk of contact with electric  current/ hot surface/ hot water<br></br>
                <input type="checkbox" name="behaviour" onChange={this.handleChange.bind(this)} value="Improper lifting, handling or moving object"/> Improper lifting, handling or moving object<br></br>
                <input type="checkbox" name="behaviour" onChange={this.handleChange.bind(this)} value="Working under the effect of alcohol/ drugs etc"/> Working under the effect of alcohol/ drugs etc<br></br>
                <input type="checkbox" name="behaviour" onChange={this.handleChange.bind(this)} value="Improper placing and stacking of object and material in dangerous location"/> Improper placing and stacking of object and material in dangerous location<br></br>
                Others:<br></br>
                <input type="text" class="form-control" name="behaviour" value={behaviour} onChange={this.onChange} placeholder="Insert details"/>
              </div>
              <div class="form-group">
                <label for="tool">Tools and Equipment: </label><br></br>
                <input type="checkbox" name="tool" value="Incorrect use of tools and equipment" /> Incorrect use of tools and equipment<br></br>
                <input type="checkbox" name="tool" value="No maintenance carried out" /> No maintenance carried out<br></br>
                <input type="checkbox" name="tool" value="Inadequate procedure" /> Inadequate procedure<br></br>
                <input type="checkbox" name="tool" value="Poor design" /> Poor design<br></br>
                <input type="checkbox" name="tool" value="Use of defective tools and equipment" /> Use of defective tools and equipment<br></br>
                <input type="checkbox" name="tool" value="Deviate from procedure" /> Deviate from procedure<br></br>
                Others:<br></br>
                <input type="text" class="form-control" name="tool" value={tool} onChange={this.onChange} placeholder="Insert details"/>
              </div>
              <div class="form-group">
                <label for="environment">Work Environment: </label><br></br>
                <input type="checkbox" name="environment" value="Poor ventilation" /> Poor ventilation<br></br>
                <input type="checkbox" name="environment" value="Poor housekeeping" /> Poor housekeeping<br></br>
                <input type="checkbox" name="environment" value="Trip hazards" /> Trip hazards<br></br>
                <input type="checkbox" name="environment" value="Poor lighting" /> Poor lighting<br></br>
                <input type="checkbox" name="environment" value="Wet floor" /> Wet floor<br></br>
                Others:<br></br>
                <input type="text" class="form-control" name="environment" value={environment} onChange={this.onChange} placeholder="Insert details"/>
              </div>
              <div class="form-group">
                <label for="action">Action: </label>
                <input type="text" class="form-control" name="action" value={action} onChange={this.onChange} placeholder="Insert action" required/>
              </div>
              <div class="form-group">
                <label for="photo">Photo URL: </label>
                <input type="text" class="form-control" name="photo" value={photo} onChange={this.onChange} placeholder="Insert photo URL" required/>
              </div>
              <div class="form-group">
                <label for="cases">Case: &nbsp;</label>
                <input type="radio" name="cases" value="Open" onChange={this.onChange}/> Open &nbsp;
                <input type="radio" name="cases" value="Close" onChange={this.onChange}/> Close
              </div>

              <button type="submit" class="btn btn-success">Submit</button>
            </form>
          </div>
        </div>
      </div>

    </div>
    );
  }
}

export default CreateForm;
import React,{Component}来自'React';
从“../config/fire”导入火;
从'react router dom'导入{Link};
从“../components/Navigation”导入导航;
类CreateForm扩展组件{
构造函数(){
超级();
this.ref=fire.firestore().collection('form');
此.state={
状态:“”,
日期:'',
时间:'',
项目:“”,
部门:'',
电话:'',
详细信息:“”,
行为:[],
工具:[],
环境:[],
行动:“”,
照片:'',
案例:“”
};
}
手变(e){
//当前选项数组
const options=this.state.options
let索引
//检查复选框是否已选中或未选中
如果(例如,选中目标){
//将复选框的数值添加到选项数组中
选项推送(+e.目标值)
}否则{
//或者从数组中删除未选中复选框中的值
index=options.indexOf(+e.target.value)
选项.拼接(索引,1)
}
//使用新的选项数组更新状态
this.setState({options:options})
}
onChange=(e)=>{
const state=this.state
状态[e.target.name]=e.target.value;
本.设置状态(状态);
}
onSubmit=(e)=>{
e、 预防默认值();
const{状态、日期、时间、项目、部门、电话、细节、行为、工具、环境、行动、照片、案例}=此状态;
此为参考添加({
地位
日期,
时间
项目
部门
电话,
细节
行为,
工具,
环境
行动,
照片,
案例
})。然后((docRef)=>{
这是我的国家({
状态:“”,
日期:'',
时间:'',
项目:“”,
部门:'',
电话:'',
详细信息:“”,
行为:[],
工具:[],
环境:[],
行动:“”,
照片:'',
案例:“”
});
this.props.history.push(“/form”)
})
.catch((错误)=>{
console.error(“添加文档时出错:”,错误);
});
}
render(){
const{状态、日期、时间、项目、部门、电话、细节、行为、工具、环境、行动、照片、案例}=此状态;
返回(

添加表单 取消 地位: 不安全行为 不安全条件 日期: 时间: 项目: 部门: 电话号码: 观察到的不安全行为和不安全条件的详细说明:

人员和风险行为:

工作场所的烦恼和闹剧

从工作场所或设备上拆除安全防护装置

任务姿势不当

接触电流/热表面/热水的风险

提升、搬运或移动物体不当

在酒精/药物等的影响下工作

在危险位置不当放置和堆放物体和材料

其他:

工具和设备:

不正确使用工具和设备

未进行任何维护

程序不充分

糟糕的设计

使用有缺陷的工具和设备

偏离程序

其他:

工作环境:

通风不良

管理不善

绊倒危险

照明不良

湿地板

其他:

行动: 照片网址: 案例: 打开 接近 提交 ); } } 导出默认的CreateForm;
我得到的是:

我想要的是:

更新日期:2019年3月13日

在句柄更改中,您将状态设置为this.state.options,但在提交处理程序中,您没有引用选项

若要解决此问题,请将其保存为您在提交表单中引用的状态值

为此,您需要传入值,以便知道要更新的内容:

handleChange(e, groupName) {...}
然后在调用该方法时传入复选框类别。因此,对于行为组中的每个复选框,按如下方式更新处理程序:

<input
 type="checkbox"
 name="behaviour"
 onChange={e => this.handleChange(e, 'behaviour').bind(this)}
 value="Annoyance and horseplay in the workplace" />
现在,当您提交行为的检查值时,将记录在行为状态键中。您可以对其他组执行相同的操作。下面是上述工作的一个示例

handleChange(e, groupName) { const options = this.state[groupName]; ... this.setState({ [groupName]: options }); }
{
status: "", 
date: "", 
time: "", 
project: "", 
department: "", 
action: "",
behaviour: [],
cases: "",
date: "",
department: "",
detail: "",
environment: [],
phone: "",
photo: "",
project: "",
status: "",
time: "",
tool: []
}