2017-07-24 13 views
2

在我的反應shouldComponentUpdate函數,this.props和nextprops具有所有相同的屬性,但它們不相等。我的代碼:在我的反應shouldComponentUpdate函數,this.props和nextprops具有所有相同的屬性,但它們不相等

shouldComponentUpdate(nextProps) { 
    console.log(this.props); 
    console.log(nextProps); 
    console.log('nextProps vs this.props:', nextProps === this.props); 
    console.log('this.props.style vs nextProps.style:', this.props.style === nextProps.style); 
    console.log('this.props.data vs nextProps.data',this.props.data === nextProps.data); 
    return true; 
    } 

輸出爲: enter image description here

我的困惑是道具是否有一些隱藏屬性。

+1

你有沒有嘗試過反應PureComponent或react-addon-shallow-比較 – Muhaimin

+0

[如何確定兩個JavaScript對象的相等性?](https://stackoverflow.com/questions/201183/how-to-determine -equality-for-two-javascript-objects) –

+0

我會試一試。謝謝你,@ Muhaimin – sunt

回答

0

對象比較不起作用。

例如採取以下代碼:

test_a = {key: 'value'} 
test_b = {key: 'value'} 
console.log(test_a == test_b) //false 

有很多方法可以正確的比較JS對象由值相等,有人在評論部分已經提供了對主題的鏈接到以前的線程。

+0

我知道如何比較兩個對象,但是在這種情況下,重點是'反應shouldComponentUpdate函數',它導入渲染性能。如果每個屬性都相等,那麼'this.props'和'nextprops'應該是相等的,那麼它就不會重新渲染。 – sunt

+0

「如果每個屬性都相同,那麼this.props和nextprops應該是相等的,」:這是不正確的。再看看我的答案。比較對象檢查它們是否佔用相同的內存地址,而不是它們的屬性是否相同。 – gravityplanx

+0

你的意思是正確的,但是兩個對象是相等的是由內存地址決定的。但是,在沒有道具屬性發生變化的情況下,「反應」不會生成新的道具,我不知道爲什麼。「https://facebook.github.io/ react/docs/react-component.html#shouldcomponentupdate」 – sunt

相關問題