简体   繁体   中英

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 .

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. 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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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