[英]How can mutating `this.state` and then immediately calling `setState` break?
據說應該將React組件的狀態視為不可變的,並且即使立即調用setState
, this.state
進行this.state
是容易出錯的。 那是,
// #1: bad...
this.state.items.push("New item");
this.setState({items: this.state.items});
// #2: good...
this.setState({items: this.state.items.concat(["New item"])});
有人可以詳細說明導致上述第一個版本失敗的確切原因嗎?
當您使用新值調用setState
時,React中的某些組件可以將新狀態與先前狀態進行比較,以檢測更改以提高性能(請參見此處: https : //facebook.github.io/react/docs/advanced-performance。 html )。 該方法稱為shouldComponentUpdate
,並接收下一個shouldComponentUpdate
和狀態進行比較。 諸如Omniscient和Om之類的某些框架都使用此框架。
在第一個示例中,您已經改變了狀態(對象和數組在JS中是按引用的),因此調用setState可能是空操作(因為狀態已經相同)。 您的組件可能不會自動重新渲染。
這是一個例子:
// Let's assume that `this.state === {numbers: [1]};` at the start
this.state.numbers.push(2);
// Oops - we just changed this.state directly,
// so now this.state === `{numbers: [1, 2]}`
// Now, react might compare the old this.state (which has been modified to [1, 2])
// to the object you're passing in (which is also [1, 2]).
// This might be a no-op.
this.setState({numbers: this.state.numbers});
在第二個示例中,MDN表示“ concat()方法返回一個包含...的新數組”,即—您沒有修改原始數組,而是完全返回了一個新數組。 在第一個示例中,.push 編輯現有數組 。
因為它是一個新數組,所以比較將始終按預期進行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.