简体   繁体   English

创建并将新对象推送到反应状态数组

[英]Creating and pushing new object into react state array

I am working on a react form with multiple form elements, and an option to repeat the whole form. 我正在处理具有多个表单元素的React表单,并提供重复整个表单的选项。 Basically a add more button which adds a new form block. 基本上,添加更多按钮可添加一个新的表单块。

To keep track of multiple forms, I created a formModel object in a different file and imported this to my react from component. 为了跟踪多个表单,我在另一个文件中创建了一个formModel对象,并将其导入到我的组件响应中。

var formModel = {
    counter : 0,
    formElements : {
        text1 : '',
        text2 : '',
        select1: '',
        radio: ''
    }
};

export default formModel;

In my component which handles the form I import it and initialize the state with 1 object of this formModel, as I need to show a minimum of one form block. 在我处理表单的组件中,我导入它并使用此formModel的1个对象初始化状态,因为我需要显示至少一个表单块。 I have a Add mode/Remove option where I add/remove a form block. 我有一个添加模式/删除选项,可以在其中添加/删除表单块。

class FormComponent extends React.Component {

    constructor(){
      super()
      this.state = {
        formList: [formModel]   
      };
    }

    addAnother(){
        let nextFormList = this.state.formList;
        nextFormList.push(formModel);
        this.setState({
            formList: nextFormList
        });
    }


    render() {
      return (
        //I map over the formList and send my form state as props into a formElement component
      );
    }
  }

My issue, is when I try to add a new object of formModel in the addAnother method into my formList array in state, it keeps adding the same initial copy of formModel. 我的问题是,当我尝试在状态中将addAnother方法中的formModel的新对象添加到formList数组中时,它会不断添加相同的formModel初始副本。

I'm unable to create a new copy of the formModel object and keep pushing the same copy. 我无法创建formModel对象的新副本并继续推送相同的副本。

I'm guessing a basic JS concept of creating objects which I'm unable to implement. 我正在猜测创建无法实现的对象的基本JS概念。

Two things you should avoid when using state: 使用状态时应避免两件事:

  1. Do not mutate objects in the current state . 不要改变当前状态下的对象 Always create new objects to update the state. 始终创建新对象以更新状态。 You can use the spread operator for that. 您可以使用散布运算符。

  2. Calls to setState are asynchronous - don't rely on this.state to reflect the new value immediately after calling setState . setState调用是异步的-调用setState后不要立即依赖this.state来反映新值 Use the callback version of setState() instead. 请使用setState()的回调版本。 React batches updates and when the update happens this.state does not contain the data from previously scheduled updates and may override them. 反应批处理更新,更新发生时, this.state不包含先前计划的更新中的数据,并且可能会覆盖它们。

Example: 例:

addAnother(){
    this.setState(oldState => ({
        formList: [...oldState.formList, formModel]
    }));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM