ReactJS setState具有多个嵌套数组 - 如何将新对象添加到子数组中

时间:2016-07-15 08:36:41

标签: react-native

如何通过setState

将新项目添加到子数组中
getInitialState : function(){
            return { 
               Todo:[
             {
               name:"parimary",
               items:[
                {item:'Todo itmd #1',isDone:false},
                {item:'Todo itmd #2',isDone:true}
               ]
             },{
               name:"Secondary",
               items:[
                {item:'Todo itmd #1',isDone:false},
                {item:'Todo itmd #2',isDone:true},
                {item:'Todo itmd #3',isDone:true}
             ]}],selectedItem:"0"};

        },


InsertItems : function(newItem){
            var item = {item:newItem,isDone:false};
            var allItems = this.state.Todo[this.state.selectedItem].items.concat([item]);
            this.setState({
                Todo: {[this.state.selectedItem]:{items:{
            $set: allItems
          }}}
            });

        },

我跑步后,我得到一个错误

  

未捕获的TypeError:allitems.map不是函数。

如何将新对象添加到子数组中?

1 个答案:

答案 0 :(得分:0)

首先,您需要安装react native addons update:

$ npm i --save react-addons-update

比在你组件中导入它:

import update from 'react-addons-update';

并使用 InsertItems 函数中的以下代码更新嵌套数组:

InsertItems : function(newItem){
     const item = {item: newItem, isDone: false};

     const index = this.state.selectedItem;

     const allItems = this.state.Todo[index].items.concat([item]);

     let newTodo = update(this.state.Todo, {
         [index]: {
             $set: {
                 ...this.state.Todo[index],
                 items: allItems
             }
         }
     });

     this.setState({Todo: newTodo});
 }