有人可以让我知道我对componentWillUnmount
我的代码缺少什么。
错误是
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
in Layout (created by RoomsPage)
in RoomsPage (created by HotExportedRoomsPage)
in AppContainer (created by HotExportedRoomsPage)
in HotExportedRoomsPage (created by PageRenderer)
看到它的次数是我们大多数人的1000倍,但我似乎无法
unmount
。我的问题代码是; componentDidMount() {
if (typeof window !== 'undefined') {
window.addEventListener('scroll', debounce(this.handleScroll, 32));
}
}
componentWillUnmount() {
if (typeof window !== 'undefined') {
window.removeEventListener('scroll', debounce(this.handleScroll, 32));
}
}
handleScroll = () => {
const scrollPositionY = +window.scrollY;
return this.setState({ scrollPositionY });
};
最佳答案
您没有删除事件侦听器,因为您正在将不同的函数传递给addEventListener
和removeEventListener
。这是因为具有相同定义的两个函数不相等。你自己看:
(() => true) === (() => true)
// false
您需要定义函数,然后将其传递。
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
handleScroll = debounce(
() => { this.setState({ scrollPositionY: +window.scrollY }) },
32
);
顺便说一句,在大多数情况下,您也不需要检查
window
或componentDidMount
中的componentWillUnmount
... SSR不会挂载组件。