問題描述1、在組件加載時,利用生命周期componentDidMount中添加事件監(jiān)聽。但在組件卸載時,在componentWillUnmount中無法移除事件2、而在Angular框架中,就是采用在組件卸載時移除事件就可以成功,而在React中此思路完全失效,為什么會有這種差異?React版本信息相關代碼class Product extends Component {
constructor() { super();
} // 組件加載時
componentDidMount() { this.scrollEvent();
} // 組件卸載時
componentWillUnmount() {
window.removeEventListener("scroll", this.onScroll.bind(this));
} // 添加事件監(jiān)聽
scrollEvent() {
window.addEventListener("scroll", this.onScroll.bind(this));
} // 事件監(jiān)聽方法
onScroll() {
console.log("滾動條正在滾動");
}
}你期待的結果是什么?實際看到的錯誤信息又是什么?1、期望結果是:在組件完成卸載時,移除事件監(jiān)聽,onScroll方法停止執(zhí)行輸出"滾動條正在滾動"字符串2、實際結果是:當前組件已經(jīng)卸載,已經(jīng)進入到另一個組件時,onScroll方法仍然在執(zhí)行輸出"滾動條正在滾動"字符串
React如何移除事件監(jiān)聽?
炎炎設計
2019-03-25 11:28:58