如何为嵌套数组和对象设置setState?

时间:2018-12-21 13:44:07

标签: javascript arrays reactjs multidimensional-array

我需要使用以下格式保存数据:

categoryselect: 0: {
  {
    question: [],
    cateName: 'checkbox'
    name: '',
    status: 1
  }
},: 1: {
  {
    question: [],
    cateName: 'checkbox'
    name: '',
    status: 1
  }
},

每当我单击新类别时,都需要在categoryselect下创建一个新对象,如果单击添加新问题,则需要在categoryselect[0].qustion[]下创建一个对象。我尝试过这种方法,但似乎并没有达到我想要的效果:

this.setState({
  categoryselect: [
    this.state.categoryselect,
    {
      question: [
        ...this.state.categoryselect.question,
        addQuestion
      ]
    }
  ],
});

2 个答案:

答案 0 :(得分:1)

看起来像categoryselect应该是一个数组,像这样:

categoryselect: [{
    question: [],
    cateName: 'checkbox'
    name: '',
    status: 1
}, {
    question: [],
    cateName: 'checkbox'
    name: '',
    status: 1
}]

这将使用相同的数字键,但最重要的是,您将拥有length属性和数组方法。

当需要添加类别时,只需执行以下操作:

this.setState({
    categoryselect: [...this.state.categoryselect, {
        question: [],
        cateName: 'checkbox'
        name: '',
        status: 1
    }]
});

...要将问题添加到第一类,请执行:

this.setState({
    categoryselect: Array.from(this.state.categoryselect, (cat, i) =>
        i != this.state.categoryselect.length-1 ? cat 
             : {...cat, ...{question: [...cat.question, addQuestion]}}
    ) 
});

答案 1 :(得分:0)

要创建所需的对象,可以使用以下脚本-

 categoryselect = {
  0: {
   {
    question: [],
    cateName: 'checkbox'
    name: '',
    status: 1
   }
  },
  1: {
   {
    question: [],
    cateName: 'checkbox'
    name: '',
    status: 1
   }
  }
 }

var allCategories = categorySelect[Object.keys(categorySelect).length] = {
 question:[...this.state.categoryselect.question,
    addQuestion],
 cateName: 'checkbox'
 name: '',
 status: 1
}

this.setState({
 categoryselect: allCategories
});