Reputation:
I'm using electron and React and I have some code that looks like this:
constructor(props) {
super(props);
const { arr } = this.props;
ipcRenderer.on('event', () => {
console.log(this.props.arr); // will log updated values
console.log(arr); // always logs initial value
});
}
Does anyone have any idea why this might be happening? I can't reproduce this anywhere else. I've tried doing similar things with window event handlers and closures to see if they behave in the same way, but they don't. Am I missing something really obvious?
const obj = { arr: [1, 2, 3] };
const { arr } = obj;
obj.arr.push(4);
arr.push(5);
console.log(obj.arr); // => [1, 2, 3, 4, 5]
console.log(arr); // => [1, 2, 3, 4, 5]
Upvotes: 3
Views: 43
Reputation: 816462
Am I missing something really obvious?
Presumably a new array is assigned to this.props.arr
. Simple repro:
const obj = { arr: [1, 2, 3] };
const { arr } = obj;
obj.arr = [1];
console.log(obj.arr); // => [1]
console.log(arr); // => [1, 2, 3]
Destructuring is nothing magical. These two are equivalent:
const { arr } = this.props;
const arr = this.props.arr;
arr
holds the value that this.props.arr
had at the time of the assignment, whereas this.props.arr
gives you the value at the time you access it.
Upvotes: 2