简体   繁体   English

为reactjs中对象内部的数组设置状态

[英]setting state for the array which is inside the object in reactjs

I am trying to do setState where I want to update the state in reactjs . 我正在尝试做setState我想在reactjs中更新状态。

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

    }
};

This is the initial state and on every entry of data ,I want all those questions to be under questions array which we have in pages. 这是初始状态,并且在数据的每个输入上,我希望所有这些问题都在页面中存在的问题数组下。 What I tried to do to achieve this ? 为了达到这个目的,我试图做些什么?

onSubmit = (data) => {
    console.log('data is ', data);
    let newForm = {
        ...this.state.form
    };
    // it shows that we can't do this as it is not iterable 
    newForm.pages.questions = [...newForm.pages.questions, ...data];


    this.setState({
        newForm
    });



}

This part of code cannot work as pages is an array. 这部分代码无法使用,因为pages是一个数组。 You have to provide the index of which page you want to modify. 您必须提供要修改的页面的索引。

newForm.pages.questions=[...newForm.pages.questions,...data];

Should be something like 应该是这样的

newForm.pages[indexOfPage].questions=[...newForm.pages[indexOfPage].questions,...data];

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

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