I'm destructuring variable from React state in render() of my class component like this:
let { indexTabPoints } = this.state;
After that I'm changing it's value:
if (condition) {
indexTabPoints += 1;
console.log(indexTabPoints); // value's changing as it should
}
And then I'm passing indexTabPoints as a prop to another component:
<PointTab
activeIndex={indexTabPoints}
....
/>
Afterwards I'm checking the value of activeIndex in PointTab component and see an old value (without any changes).
It seems to me, that React does not update the prop I'm passing to PointTab component, whenever it's changing or not. Why is this happening and how to avoid it, using destructuring?
Edited: I've just noticed that i got several child components and the other one (in another place) was telling me that the value is old (because for it the value did not change). Thank you all guys for help, forgive me my carelessness.
Props are immutable
And you can't update state like indexTabPoints += 1;, instead you can do like this.setState((prev) =>({indexTabPoints: prev+1})), and you shoul not log states value just after setting it since setState is asynchronous while the console.log is executed immediately
Can try this (but just for debugging):
if (condition) {
indexTabPoints += 1;
setTimeout(() => console.log(indexTabPoints), 1000);
}
example for debugging to understand if component is called before if condition:
if (condition) {
indexTabPoints += 1;
console.log("in if condition" + indexTabPoints);
}
render(){
return(
{
console.log(" in render" + indexTabPoints)
}
<PointTab
activeIndex={indexTabPoints}
....
/>);
}