如何在ReactJS中的嵌套对象中设置状态?

时间:2020-02-26 17:42:00

标签: javascript reactjs

我正在尝试在2个数组的对象中setState。每个数组都有其自己的对象。我正在尝试创建新的组和行onClick的按钮。因此,我有一个名为groups的对象,它有一个名为firstGroup的数组,然后是另一个名为secondGroup的数组。我有一个点击监听器handleSecondGroup,该监听器应该向secondGroup添加一个新行。但是在secondGroup上执行setState似乎不起作用。不知道如何实现。

这是我的代码的样子:-

这是App.vue文件

import React, {Component} from 'react';
import './App.css';
class App extends Component {
 state = {
    groups {
         firstGroup: [
             { id: 0, title: 'New Group', rows: [{ id: 0,value: 'row1', options: 
        [1,2,3,4,5]}] }
          ],
         secondGroup: [
             {id:0 , title: 'New Group', options: [1,2,3,4,5] }
          ]
      }
 }

handleSecondGroup = () => {
   const groups = [...this.state.groups.secondGroup, { id:this.state.groups.length, title: 'New Second Group', options: [1,2,3,4,5}]
    this.setState({
  groups
 })
console.log(groups)
}

  export default App;

我不确定这是否是嵌套对象中setState的正确方法?任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

我不确定是否要添加第三组,但这是添加任意第三组的实际示例:

const thirdGroup = {
  id: 3,
  title: 'New Third Group',
  options: [1]
};

class App extends Component {
  state = {...}

  handleSecondGroup = () => {
    this.setState(prevState => {
      const prevGroups = prevState.groups;
      return { groups: { ...prevGroups, thirdGroup } };
    });
  };

  render() {
    return (
      <>
        <pre>{JSON.stringify(this.state.groups, null, 2)}</pre>
        <button onClick={this.handleSecondGroup}>Add Group</button>
      </>
    );
  }
}

Edit young-platform-2xsvo

答案 1 :(得分:0)

您仅用更新的secondGroup替换组。首先复制groups对象,然后更新嵌套数组。和选项:[1,2,3,4,5]缺少方括号。

handleSecondGroup = () => {
    const groups = {...this.state.groups, secondGroup: [...this.state.groups.secondGroup, { id:this.state.groups.length, title: 'New Second Group', options: [1,2,3,4,5]}]}
    this.setState({ groups })
    console.log(groups)
}

答案 2 :(得分:0)

您尝试setState使用的结果对象的结构不正确。

export default class App extends Component {
    state = {
        groups : {
            firstGroup: [
                { 
                    id: 0, 
                    title: 'New Group', 
                    rows: [
                        { 
                            id: 0,
                            value: 'row1', 
                            options: [1,2,3,4,5]
                        }
                    ] 
                }
            ],
            secondGroup: [
                {
                    id:0, 
                    title: 'New Group', 
                    options: [1,2,3,4,5] 
                }
            ]
        }
    }

    handleSecondGroup = () => {
        const groups = { ...this.state.groups };

        groups.secondGroup.push({
            id: groups.secondGroup.length, 
            title: 'New Second Group', 
            options: [1,2,3,4,5]
        });

        this.setState({ groups });
    }
}