[英]React Warning: Can't call setState (or forceUpdate) on an unmounted component
[英]Using forceUpdate instead of setState in React?
如果我有一個反應組件,我只是設置它的類變量,即
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.numberElements = 20;
this.color = 'red';
}
render() {
...
}
}
我不能只調用this.forceUpdate()
來發出重新渲染(每當我更新我的類變量時)而不是維護狀態並調用setState
嗎? 或者這樣做不好,如果是這樣,為什么?
forceUpdate()
實際上在您所描述的場景中很有用。
從文檔:
默認情況下,當您的組件的狀態或道具發生變化時,您的組件將重新渲染。 如果您的
render()
方法依賴於其他一些數據,您可以通過調用forceUpdate()
告訴 React 該組件需要重新渲染。
但需要注意的是,它會跳過shouldComponentUpdate()
,因此您無法獲得優化優勢。
此外,使用forceUpdate()
“繞過”正確的生命周期,使您的代碼不那么直接,並且可能更難理解和維護。
因此建議盡可能使用state
和props
。
通常你應該盡量避免使用 forceUpdate() 並且只在 render() 中讀取
this.props
和this.state
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.