1、在组件加载时,利用生命周期componentDidMount中添加事件监听。但在组件卸载时,在componentWillUnmount中无法移除事件
2、而在Angular框架中,就是采用在组件卸载时移除事件就可以成功,而在React中此思路完全失效,为什么会有这种差异?

class Product extends Component {
constructor() { super();
} // 组件加载时
componentDidMount() { this.scrollEvent();
} // 组件卸载时
componentWillUnmount() {
window.removeEventListener("scroll", this.onScroll.bind(this));
} // 添加事件监听
scrollEvent() {
window.addEventListener("scroll", this.onScroll.bind(this));
} // 事件监听方法
onScroll() {
console.log("滚动条正在滚动");
}
}1、期望结果是:在组件完成卸载时,移除事件监听,onScroll方法停止执行输出"滚动条正在滚动"字符串
2、实际结果是:当前组件已经卸载,已经进入到另一个组件时,onScroll方法仍然在执行输出"滚动条正在滚动"字符串
炎炎设计
弑天下
随时随地看视频慕课网APP
相关分类