首页 > 解决方案 > 在 setstate 之前复制和更新嵌套对象。反应式

问题描述

我在我的状态下嵌套了对象:

constructor(props) {
    super(props);
    this.state = {
        aba1Array: [
            {
                item:[
                       {
                         id: 1,
                         nome: "apple",
                         selected:false,
                       },
                       {
                         id: 2,
                         nome: "juice",
                         selected:false,
                       }
                     ]
             },
             {
                item:[
                       {
                        id: 3,
                        nome: "apple",
                        selected:false,
                       },
                       {
                        id: 4,
                        nome: "juice",
                        selected:false,
                       }
                     ]
              }
              ],
             };
}

现在我想复制数组,更新一个项目,然后再次 setState(这是正确的更新方法,对吗?),该怎么做?这是我当前的代码:

updateItem(id){
    let newItems = Object.keys(this.state.aba1Array).map((subitem) => {
    subitem.item.map((item) => item.id===id ? {...item, selected: true } : item);
    });
    this.setState({ aba1Array: newItems });
}

这正在返回:TypeError:未定义不是对象(评估'subitem.item.map')

编辑:当我添加第二层嵌套时,问题就开始了,在它只用一层就可以正常工作之前,就像这样:

let newItems = Object.keys(this.state.aba1Array).map((item) => {
         item.id===id ? {...item, selected: true } : item);

编辑2:在我只列出项目的屏幕的另一部分,我正在使用:

listItem() { return this.state.aba1Array.map((subitem)=> { return ( subitem.item.map((item) => { return ( <View> ...

它工作正常。为什么在更新功能中它给了我错误?我不明白

编辑3: - 解决方案 -

我的解决方案是使用库对象路径不可变:

updateItem(itemIndex,subIndex){
        const newObj = immutable.update(this.state.aba1Array, [subIndex,'item', itemIndex , 'selected' ], v => true );
        this.setState({ aba1Array: newObj });
    }

标签: javascriptreactjsreact-native

解决方案


最佳解决方案:我忘了在 map 函数上返回值,所以新数组没有得到对象的完整树,最好的解决方案是:

 let newItems = this.state.aba1Array.map((subitem) => {
            subitem.item.map((item) => {
                item.selected = true;
                return item;
            })
            return subitem;
    });

推荐阅读