每次onClick
执行时,我都会收到有关内存泄漏的警告消息。如何使用钩子从我的功能组件中的Context.Consumer取消订阅组件?useEffect
我没有找到如何取消订阅 AppContext 的方法。AppContext.unsubsribe()
不工作。
import React, {useState, useContext} from 'react';
import {withRouter} from 'react-router-dom';
import axios from 'axios';
import {AppContext} from "../context/AppContext";
const LoginPage = (props) => {
const [name, setName] = useContext(AppContext);
const [isLoading, setIsLoading] = useState(false);
const onClick = () => {
setIsLoading(true);
axios.post('/get-name')
.then(resp => {
setName(resp);
setIsLoading(false);
props.history.push('/');
})
.catch(err => console.log(err))
.finally(() => setIsLoading(false));
};
return (
<div>
<button onClick={onClick}></button>
</div>
);
};
export default withRouter(LoginPage);
浏览器控制台中的错误消息:
警告:无法对未安装的
组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要解决此问题,请在 useEffect 清理函数中取消所有订阅和异步任务。在 UserPage 中(由 Context.Consumer 创建) 在 Route 中(由 withRouter(UserPage) 创建) 在 withRouter(LoginPage) 中(由 Context.Consumer 创建) 在 Route 中(由 UserRoute 创建)