![](/img/trans.png)
[英]Do I need to unbind all event listeners on my React components in componentWillUnmount
[英]Do you need to unbind/remove event listeners when navigating away from a React page?
我正在React中制作一個Web應用程序。 我目前有頁面A和頁面B。頁面A具有綁定到頁面上各種元素的幾個事件偵聽器。 但是,當我從頁面A導航到頁面B時,我的控制台中反復出現以下錯誤(例如幾秒鍾內出現數十個錯誤):
警告:setState(...):只能更新已安裝或正在安裝的組件。 這通常意味着您在未安裝的組件上調用了setState()。 這是無人值守。 請檢查LandingPageHeader組件的代碼。
我是否需要在我的componentWillUnmount()函數(位於A頁)中取消綁定這些偵聽器? 還是發生了其他事情? 此外,將某些事件偵聽器綁定到html標簽是否重要?
還應注意,上述事件偵聽器的某些事件處理程序確實執行涉及更新/設置React狀態的功能。
是的,您可以在componentWillUnmount
解除綁定事件偵聽器,或者在A頁組件中設置一個標志,每次在setState之前檢查此標志。
componentDidMount() {
var _this = this;
this._mounted = true;
// in listenner function
window.addEventListener('resize', funciton () {
if (_this._mounted) {
_this.setState({});
}
});
}
componentWillUnmount() {
this._mounted = false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.