2017-02-01 108 views
3
解構分配出現異常行爲古怪

我使用的是電子和反應,我有一些代碼,看起來像這樣:對象的構造

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] 

回答

3

我思念的東西真的很明顯?

想必陣列分配給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當時給你的價值,你訪問它。

+0

謝謝!就是這樣。 – epiqueras