首页 > 解决方案 > 在 reactjs 中更新嵌套状态

问题描述

我有这个嵌套的状态,我很难设置状态。错误:未定义不是对象(评估 this.state.form) 我的初始状态是:

this.state={
    activePage:0,
    visible:false,
    questionType:null,
    form:{
        title:'',
        description:'',
        pages:[{
            title:'',
            description:'',
            questions:[

            ]
        }]
    }
};

现在每次用户点击时,我都需要向 pages 数组添加更多对象,这些对象应该有标题 ( '')、描述 ( '') 和问题(空列表)。我试图实现这一点,但它似乎并没有奏效。

let newForm={
     ...this.state,
     form:{
          ...this.state.form,
          pages:[
               ...this.state.form.pages,
               pageData
          ]
     }
 };
 console.log('newForm',newForm);
 this.setState({
     form:newForm
 });

这就是我的 pageData 的样子

let pageData={
    title:'',
    description:'',
    questions:[]
};

标签: javascriptreactjs

解决方案


您将整个设置statenewForm. 只需将其限制为form对象:

let newForm = {
  ...this.state.form,
  pages: [
    ...this.state.form.pages,
    pageData
  ]
};

console.log('newForm', newForm);

this.setState({
  form: newForm
});

推荐阅读