我有点卡住了。我尝试使用另一个数组中的另一个对象覆盖数组中的某个对象:
onStepsLayoutChange = (layout) => {
console.log("The new layout is", layout); //Array
this.setState((prevState) => ({
layout: layout,
stepsData: prevState.stepsData.map(step => {
layout.map(l => {
if(step.identifier === parseInt(l.i)){
console.log("Match", l, step); // "l" is not empty and actually matches only if "id" is identical
return {
...step,
layout: l //I want to override "layout" with the current layout "l"
}
}
});
return step
})
}), () => console.log("LayoutChange:", this.state.layout, this.state.stepsData)); // "layout" in each step is empty
};
在这种情况下,我的失败是什么?
答案 0 :(得分:1)
如果stepsData必须是数组数组,则会忘记返回:
onStepsLayoutChange = (layout) => {
console.log("The new layout is", layout); //Array
this.setState((prevState) => ({
layout: layout,
stepsData: prevState.stepsData.map(step => {
return layout.map(l => { //here <---
if(step.identifier === parseInt(l.i)){
console.log("Match", l, step); // "l" is not empty and actually matches only if "id" is identical
return {
...step,
layout: l //I want to override "layout" with the current layout "l"
}
}
});
return step
})
}), () => console.log("LayoutChange:", this.state.layout, this.state.stepsData)); // "layout" in each step is empty
};
答案 1 :(得分:1)
问题是,您缺少#array.map的默认行为。对于每个数组值,映射将默认返回一些值undefined
。你正在map中运行map,所以stepData的最终值是:
[[...], [...], [....] ....]
不使用嵌套地图,而是使用#array.findIndex或#array.find并返回值。
像这样写:
stepsData: prevState.stepsData.map(step => {
let index;
index = layout.findIndex(l => step.identifier === parseInt(l.i));
if(index >= 0){
return {
...step,
layout: layout[index]
}
}
return step;
})
检查此代码段:
let a = [1,2,3,4,5];
let b = [2,3];
let result = a.map(i => {
return b.map(j => {
if(i === j)
return 0;
})
return i;
})
console.log(result);