[英]React: Is it possible to prevent state update after unmount, via setting this.setState to empty function?
我面臨的問題是,網絡回調正在嘗試對已卸載組件的setState()進行設置,並收到有關此無操作的默認控制台警告。
我無法跟蹤為什么會發生卸載,但是我找到了一個解決方案,建議在componentWillUnmount()中將函數設置為空。 它沒有用,我測試了將this.setState設置為空。 見下文。
錯誤消失了,但我想問一問這是否是有效的解決方案。 這里的代碼:
componentDidMount() {
this.fetchLogItems(10, 'recentChanges');
}
componentWillUnmount() {
this.setState = () => {};
}
fetchLogItems = (limit, stateRef) => {
let tmpObj = {};
base.fetch('_changelogs', {
context: this,
then(data) {
tmpObj[stateRef] = {...data}
tmpObj.loading = false;
this.setState({...tmpObj})
},
catch(err){console.error(err)}
});
};
兩種選擇:
如果您的庫允許“取消”,“銷毀”或“清理”,那么您可以簡單地執行以下操作:
componentWillUnmount() {
base.cancelFetch(); // or something similar.
}
否則,您可以向您的組件引入類屬性。 也許將其命名為isUnmounted
。 在componentWillUnmount
, this.isUmounted
設置為true。 將this.setState
調用包裝在if
-statement中,該語句檢查isUnmounted
是否為false,如果為false,則可以調用this.setState
。 這實際上是一種非常常見的模式。
它可以“ 感覺 ”丑,但是,通過事實上的,這種格局似乎陣營開發者慣用的。 如果不是這樣,至少對於與您類似的問題,這是一種務實的解決方案。
constructor() {
// HERE
this.isUmounted = false;
}
componentDidMount() {
this.fetchLogItems(10, 'recentChanges');
}
componentWillUnmount() {
// HERE
this.isUmounted = true;
}
fetchLogItems = (limit, stateRef) => {
let tmpObj = {};
base.fetch('_changelogs', {
context: this,
then(data) {
tmpObj[stateRef] = {...data}
tmpObj.loading = false;
// WRAP THE `this.setState` here.
if (!this.isUnmounted) {
this.setState({...tmpObj})
}
},
catch(err){console.error(err)}
});
};
但是,我更喜歡使用支持取消的庫和助手。 絕對可以保證一定程度的清理。 如果不取消,我們就有引入內存泄漏的風險。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.