I must be doing something dumb here, but after a day of trying to figure it out, I am turning here...
I have a dropdown menu for each element of an array val which I save in the Component state:
class C extends Component {
state = { val : [ 1,2,3,4] }
...
}
where a change in each of the dropdown entries triggers this callback:
onChanged = (event, index) => {
console.log("val changed");
this.setState(state => {
const val = state.val;
val[index] = event.target.value;
return { val: val };
});
};
Now the issue is that I can't figure out how to detect this change in shouldComponentUpdate. Specifically, when I change one of the dropdown options, I see val changed being logged. However, in the shouldComponentUpdate method, the nextState and this.state always contain the same values (and appear to be identical on comparison). So there is no way for me to detect a change in shouldComponentUpdate. Here is the exact code I am using:
shouldComponentUpdate(nextProps, nextState) {
console.log(
"shouldComponentUpdate",
nextProps.val,
this.state.val,
nextState.val,
this.state.val === nextState.val
);
return false;
}
Before a change in one of the dropdown options, this logs something like
shouldComponentUpdate, undefined, [1, 2, 3, 4], [1, 2, 3, 4], true
If I change the first dropdown from 1 to 9, then I see
shouldComponentUpdate, undefined, [9, 2, 3, 4], [9, 2, 3, 4], true
I expected that immediately after the change I would see
shouldComponentUpdate, undefined, [1, 2, 3, 4], [9, 2, 3, 4], true
Please tell me how I can detect a change in shouldComponentUpdate or what idiom I should be using.
EDIT:
It was suggested that I slice the value array in the onChanged callback, that is, change to callback to:
onChanged = (event, index) => {
console.log("val changed");
this.setState(state => {
const val = state.val.slice();
val[index] = event.target.value;
return { val: val };
});
};
That did not fix the issue. Here is the console log before and after a change:
shouldComponentUpdate undefined (4) [1, 2, 3, 4] (4) [1, 2, 3, 4] true
val changed
shouldComponentUpdate undefined (4) [9, 2, 3, 4] (4) [9, 2, 3, 4] true
EDIT:
Crikeys I am dumb. There was a dumb return statement that was getting hit. I totally missed it. I am accepting the answer below since they are correct as the problem was stated.