[英]useEffect cleanup function in react
我收到此警告“无法在未安装的组件上执行 React state 更新。 这是一个无操作,但它表明您的应用程序中存在 memory 泄漏。 要修复,请取消 useEffect 清理 function 中的所有订阅和异步任务。
代码
const [photo, setPhoto] = useState([]);
useEffect(() => {
fetch('/mypost', {
headers: {
cookie: 'access_token',
},
})
.then((res) => res.json())
.then((data) => {
setPhoto(data.mypost);
});
}, []);
数据已获取,但我不知道要在清理中添加什么。 有什么建议么?
问题是获取请求已解决,但组件已卸载(出于某种原因),因此现在无法进行 state 更新。
您需要使用Abort Controller来取消进行中的请求。 如果组件卸载,效果清理 function 会取消获取请求。
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
拒绝。
您可能需要在某处发现此 promise 拒绝。 您可以将 append 一个.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);
试试下面的代码:
useEffect(() => {
let isMounted = true;
fetch('/mypost', {
headers: {
cookie: 'access_token',
},
})
.then((res) => res.json())
.then((data) => {
if (isMounted) setPhoto(data.mypost);
});
//cleanup function
return () => { isMounted = false };
}, []);
import React, {useState} from "react";
import { useAsyncEffect } from "use-async-effect2";
import cpFetch from "cp-fetch";
export default function TestComponent(props) {
const [photo, setPhoto] = useState([]);
useAsyncEffect(
function* () {
const response = yield cpFetch('/mypost');
setPhoto((yield response.json()).mypost);
},
[]
);
return <div></div>;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.