I've got a question concerning the rendering behavior of those two options:
export function saveOrCancelStepContentComponents(stepIndex, targetArray, newArray) {
// Option 1
let stepsData = this.state.stepsData.slice();
stepsData[stepIndex][targetArray] = newArray;
this.setState({stepsData: stepsData}, () => {
console.log("saveStepConditions[]:", this.state.stepsData[stepIndex][targetArray]);
});
// Option 2
this.setState((prevState) => ({
stepsData: prevState.stepsData.map((currentStep, i) => {
if (i === stepIndex) {
return {
...currentStep,
[targetArray]: newArray,
}
}
return currentStep
})
}), () => {
console.log("saveStepConditions[]:", this.state.stepsData[stepIndex][targetArray]);
});
}
Canceling and saving works with both options, which is to say that the console.logs are fine. However, only option 2 re-renders the page. Going with option 1 won't result in any phenotype changes. Any ideas why that is? Thanks!
This line stepsData[stepIndex][targetArray] = newArray;
mutates stepsData[stepIndex]
object instead of creating a new one.
It should be like
stepsData[stepIndex] = {
...stepsData[stepIndex],
[targetArray]: newArray
}
The same way you did inside map function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.