我在更改数组内对象的属性时又遇到了问题,但这次是数组中数组中的数组...
我在更改图片预览方面遇到了问题。
这没有效果:
return {
...picture,
preview: "hallo"
}
完整的代码是:
this.setState((prevState) => ({
stepsData: prevState.stepsData.map(step => {
if (step.identifier === stepIdentifier) {
console.log("lkkljk",step)
step.onChangeContentComponents.map(
contentComponent => {
if (contentComponent.pictures !== null){
console.log(contentComponent.pictures);
console.log(contentComponent.pictures[0].preview);
contentComponent.pictures.map(picture => {
return {
...picture,
preview: "hallo"
}
});
}
return contentComponent
}
);
return {
...step,
[targetArray]: newArray,
}
}
return step
})
}), () => {
console.log(this.state.stepsData)
});
感谢。
答案 0 :(得分:1)
问题是step.onChangeContentComponents.map
调用的返回值没有在任何地方使用。您必须将代码更改为
this.setState((prevState) => ({
stepsData: prevState.stepsData.map(step => {
if (step.identifier === stepIdentifier) {
console.log("lkkljk",step)
var newStep = step.onChangeContentComponents.map(
contentComponent => {
if (contentComponent.pictures !== null){
console.log(contentComponent.pictures);
console.log(contentComponent.pictures[0].preview);
contentComponent.pictures.map(picture => {
return {
...picture,
preview: "hallo"
}
});
}
return contentComponent
}
);
return newStep
}
return step
})
}), () => {
console.log(this.state.stepsData)
});
但是我建议你不要在setState中进行复杂的计算,并抽象出
之外的计算var stepsData = [...this.state.stepsData];
stepsData = stepsData.map(step => {
if (step.identifier === stepIdentifier) {
var newStep = step.onChangeContentComponents.map(
contentComponent => {
if (contentComponent.pictures !== null){
console.log(contentComponent.pictures);
console.log(contentComponent.pictures[0].preview);
contentComponent.pictures.map(picture => {
return {
...picture,
preview: "hallo"
}
});
}
return contentComponent
}
);
return newStep
}
return step
});
this.setState({stepsData}, () => {
console.log(this.state.stepsData)
});
答案 1 :(得分:1)
尝试使用immutability-helper util来解决它。
此前,此util已包含在react-addons-update模块中。
答案 2 :(得分:0)
let stepsData = [...this.state.stepsData];
stepsData = stepsData.map(step => {
if (step.identifier === stepIdentifier) {
return {
...step,
[targetArray]: newArray,
onChangeContentComponents: step.onChangeContentComponents.map(contentComponent => {
if (contentComponent.pictures !== null) {
return {
...contentComponent,
pictures: contentComponent.pictures.map(picture => {
console.log(picture)
return {
...picture,
preview: "hallo"
}
})
}
}
return contentComponent
}
)
}
}
return step
});
this.setState({stepsData: stepsData}, () => {
console.log(this.state.stepsData)
});