reactjs - react中的useEffect清理功能
问题描述
我收到此警告“无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要修复,请取消 useEffect 清理函数中的所有订阅和异步任务。
代码
const [photo, setPhoto] = useState([]);
useEffect(() => {
fetch('/mypost', {
headers: {
cookie: 'access_token',
},
})
.then((res) => res.json())
.then((data) => {
setPhoto(data.mypost);
});
}, []);
数据已获取,但我不知道要在清理中添加什么。有什么建议么?
解决方案
问题
问题是获取请求已解决,但组件已卸载(出于某种原因),因此现在无法进行状态更新。
解决方案
您需要使用Abort Controller来取消正在进行的请求。如果组件卸载,效果清理函数会取消获取请求。
useEffect(() => {
const controller = new AbortController(); // <-- create controller
const { signal } = controller; // <-- get signal for request
fetch('/mypost', {
headers: {
cookie: 'access_token',
},
signal, // <-- pass signal with options
})
.then((res) => res.json())
.then((data) => {
setPhoto(data.mypost);
});
return () => controller.abort(); // <-- return cleanup function to abort
}, []);
注意:当
abort()
被调用时,fetch()
promise 会以AbortError
.
您可能需要在某个地方捕捉到这个承诺拒绝。您可以将一个块附加.catch
到 Promise 链。
fetch('/mypost', {
headers: {
cookie: 'access_token',
},
signal, // <-- pass signal with options
})
.then((res) => res.json())
.then((data) => {
setPhoto(data.mypost);
})
// catch any rejected fetch promises (including aborted fetches!)
.catch(console.error);
推荐阅读
- javascript - 单击标签元素内的文本时,Javascript 事件侦听器会触发两次
- html - css:并排显示 div 时的奇怪行为
- java - 将 Github 库添加到 Android 项目
- javascript - 来自特定网址的 Firebase 安全规则存储
- python - python tkinter 可滚动框架
- c++ - 为嵌套模板类声明 operator==
- typescript - 如何使用 Typescript 键入嵌套的 ES6 映射树
- c# - 根据流程架构更改变量类型和值
- android - 在 Android 设备上的应用程序中隐藏默认导航栏
- scala - Some 的 Apache Spark 过滤器