Skip to main content

FAQ

react hook组件卸载数据处于加载中渲染组件状态

原因: 在React开发中,我们可能经常会遇到这个一个警告: react_devtools_backend.js:2540 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.

React防止出现内存泄漏,意思为:我们不能在组件销毁后设置state或者发起异步请求,我们应该在组件销毁的时候将异步请求撤销

定时器情况

const [update, setUpdate] = useState(1); useEffect(() => {
const creatInt = setInterval(() => { //假设这里写了定时器来更新update
setUpdate(c => c + 1);
}, 2000);
return () => {
clearInterval(creatInt); //(重点)这里清除掉定时器
};
}, []);
  • useSate情况
useEffect(() => {
let isUnmount = false; //这里插入isUnmount
const fetchDetail = async () => {
const res = await getDetail(detailId);
if (res.code === 0 && !isUnmount) { //加上判断isUnmount才去更新数据渲染组件
setDetail(res.data);
}
};
fetchDetail();
return () => isUnmount = true; //最好return一个isUnmount
}, [detail]);

说明:useEffect相当于class组件的3个生命周期,其中return ()=>{ } 相当于 componentWillUnMount

  • class类组件

原理同hook在 componentWillUnMount 中设置一个 值true 、false来判断是否渲染组件

参考

弃用通知:React 18 不再支持 ReactDOM.render