构造函数中的对象解构赋值表现异常

3

我正在使用electron和React,我有一些类似以下代码的东西:

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 
  });
}

有人知道为什么会出现这种情况吗?我在其他地方无法复现这个问题。我尝试使用窗口事件处理程序和闭包来做类似的事情,看看它们是否表现相同,但它们没有。我是不是漏掉了非常明显的东西?

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]
1个回答

2

我是否遗漏了一些非常明显的东西?

很可能是给this.props.arr分配了一个新的数组。简单的复现:

const obj = { arr: [1, 2, 3] };
const { arr } = obj;
obj.arr = [1];

console.log(obj.arr); // => [1]
console.log(arr); // => [1, 2, 3]

解构不是什么神奇的东西。下面两种写法是等价的:

const { arr } = this.props;
const arr = this.props.arr;

arr保存了this.props.arr在赋值时的值,而this.props.arr则给出了您在访问它时的值。


谢谢!就是这样。 - user5183133

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接