gpt4 book ai didi

javascript - 无法使用 EventListener 对未安装的组件执行 React 状态更新

转载 作者:行者123 更新时间:2023-12-05 01:53:44 32 4
gpt4 key购买 nike

我有以下代码,我收到了两个警告:

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 a useEffect cleanup function.

unmountComponentAtNode(): The node you're attempting to unmount was rendered by another copy of React.

    import React, { useState, useEffect } from "react";
import GravatarList from "./GravatarList";
import Header from "./Header";
import { calculateNumberOfImages } from "./utils";

const App = () => {
const handle = () => {
setState({ images: calculateNumberOfImages() });
}


useEffect(() => {
return () => {

window.removeEventListener('resize', () => handle())
window.removeEventListener('scroll', () => handle())
}
}, [])


const [state, setState] = useState(() => {

window.addEventListener("scroll", () => handle());
window.addEventListener("resize", () => handle());

return { images: calculateNumberOfImages() };
});

return (
<div>

<Header />
<GravatarList state={state} />
</div>
);
};

export default App;

我似乎无法弄清楚我做错了什么,因为我已经在 useEffect 中清除了监听器。

最佳答案

这里的问题是您尝试删除的事件回调不是您一开始添加的回调。问题是因为您正在使用匿名函数来调用函数更新状态。

您也不应该使用状态初始化函数来产生副作用,例如添加事件监听器。

handle 回调和事件监听器添加到挂载的 useEffect Hook 中。将 handle 回调引用传递给添加/删除函数,

const App = () => {
const [state, setState] = useState(() => ({
images: calculateNumberOfImages()
}));

useEffect(() => {
const handle = () => {
setState({ images: calculateNumberOfImages() });
};

window.addEventListener("scroll", handle);
window.addEventListener("resize", handle);

return () => {
window.removeEventListener('resize', handle);
window.removeEventListener('scroll', handle);
}
}, []);

return (
<div>
<Header />
<GravatarList state={state} />
</div>
);
};

关于javascript - 无法使用 EventListener 对未安装的组件执行 React 状态更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71055394/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com