Reputation: 2017
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!
Upvotes: 0
Views: 51
Reputation: 45121
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.
Upvotes: 2