Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 通过扩展算子进行反应状态操作_Reactjs - Fatal编程技术网

Reactjs 通过扩展算子进行反应状态操作

Reactjs 通过扩展算子进行反应状态操作,reactjs,Reactjs,我有一个初始状态: this.state = { formInfo: { name: '', age: '', height: '' }, errorMessage: '' } 编辑表单时,状态应更新,这就是我目前的处理方式: handleInputChange = e => { const { name, value } = e.target this.setState({ ...t

我有一个初始状态:

this.state = {
    formInfo: {
        name: '',
        age: '',
        height: ''
    },
    errorMessage: ''
}
编辑表单时,状态应更新,这就是我目前的处理方式:

handleInputChange = e => {
    const { name, value } = e.target
    this.setState({
        ...this.state,
        formInfo: {
            ...this.state.formInfo,
            [name]: value
        }
    })
}
如果这个过程不符合行业标准,你能为我提供一个更好的解决方案来操纵国家吗


我怀疑是否有更有效的方法来存档此文档。

如果您想了解最佳实践,那么下面就是其中之一。你的代码很好。最好避免使用点符号,并提供默认值

handleInputChange = e => {
  const {
    target: {
      name = '',
      value = '',
    } = {},
  } = e;

  const {
    formInfo,
  } = this.state;

  this.setState({
    formInfo: {
      ...formInfo,
      [name]: value,
    },
  });
}

如果您关心的是处理比您的示例复杂得多的对象,那么可以研究immer()。