尝试将对象推入数组时使用 onSubmit 的更好方法

better way to use onSubmit when trying to push object in to an array

我正在尝试编写一种更有效的方法来使用新对象设置状态数组,我的状态是这样的:

 state = {
    names: [],
    tempName: {
      name: '',
      mail: ''
    }
  };

我在提交时是这样使用的:

 onSubmit = e => {
    e.preventDefault();
    const inputs = [...this.state.names, this.state.tempName];
    const tempName = { name: '', mail: ''};
    this.setState({ inputs, tempInput });

};

我希望像这样缩短一些时间:

    onSubmit = e => {
      e.preventDefault();
      const { tempName } = this.state.tempName;
      this.setState(curr => ({
       names: [{ ...curr.names, tempName }]
    }));
  };

但我得到的只是对数组内对象的引用,是否有比上述方法更好的方法?

您可以在对象上使用 spread operator 将其可枚举属性复制到新对象上。

onSubmit = e => {
  e.preventDefault();
  this.setState(currentState => ({
    names: [...currentState.names, {...currentState.tempName}],
    tempName: {
      name: '',
      mail: ''
    }
  }));
};