javascript - 在 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 });
}
解决方案
最佳解决方案:我忘了在 map 函数上返回值,所以新数组没有得到对象的完整树,最好的解决方案是:
let newItems = this.state.aba1Array.map((subitem) => {
subitem.item.map((item) => {
item.selected = true;
return item;
})
return subitem;
});
推荐阅读
- react-native - 如何在 React Native 中下载资产图像?
- jasper-reports - 如何更改 adobe reader 的缩放级别?
- django - 如何从 django 查询中获取 sql 等效查询?
- java - 对如何将 txt 文件写入字符串然后将其转换为二维数组感到困惑
- qr-code - 用于识别分隔页的条形码
- html - 如何使用 col-sm 内联?
- azure - Databricks 文件存储 = 0
- android - Android应用程序忽略用户应用程序权限
- c++ - 我需要帮助修复 C++ 空白检测器
- javascript - 如何解决 ChartJS 甜甜圈选项中的语法错误?