提问人:GoonGamja 提问时间:12/5/2022 更新时间:12/5/2022 访问量:129
为什么 removeEventListener 没有删除在 componentWillUnmount 生命周期内返回箭头函数的箭头函数?(反应.js)
Why the arrow function that returns arrow function inside componentWillUnmount lifecycle is not removed by removeEventListener? (React.js)
问:
我目前正在研究React.js类组件。
我在componentDidMount中使用addEventListener添加了侦听器,如下所示。
componentDidMount() {
document.addEventListener('copy', this.copyBlock('copy'));
document.addEventListener('cut', this.copyBlock('cut'));
}
componentWillUnmount() {
document.removeEventListener('copy', this.copyBlock('copy'));
document.removeEventListener('cut', this.copyBlock('cut'));
}
// This is the function that added by addEventListener.
// As you can see, argument copyType is passed to copyBlock function and returns event object.
copyBlock = (copyType: 'copy' | 'cut') => (e: ClipboardEvent) => {
if (e.target !== document.body) {
return;
}
const {
type,
libraryStore: { showUtilBlock },
} = this.props;
BlockUtil.copyBlock(e, copyType);
};
但是,这就是问题所在。
卸载组件时,应删除该函数。然而,事实并非如此。
但是,当我像下面这样更改 copyBlock 函数时,它可以工作。它被删除。
componentDidMount() {
document.addEventListener('copy', this.copyBlock);
}
componentWillUnmount() {
document.removeEventListener('copy', this.copyBlock);
}
copyBlock = (e?: ClipboardEvent) => {
if (e.target !== document.body) {
return;
}
const {
type,
libraryStore: { showUtilBlock },
} = this.props;
BlockUtil.copyBlock(e, 'copy');
};
有什么区别?为什么 eventListener 在返回函数的箭头函数上不起作用?
答:
3赞
Lin Du
12/5/2022
#1
因为每次调用 .它们中的每一个都有不同的指针。传入的事件处理程序应与传入的事件处理程序相同。(相同的指针)this.copyBlock()
removeEventListener()
addEventListener()
试试这个:
constructor() {
this.copy = this.copyBlock('copy');
this.cut = this.copyBlock('cut');
}
componentDidMount() {
document.addEventListener('copy', this.copy);
document.addEventListener('cut', this.cut);
}
componentWillUnmount() {
document.removeEventListener('copy', this.copy);
document.removeEventListener('cut', this.cut);
}
评论