有一个配置文件页面。在这里,每次我访问个人资料时都会加载props.profile()
。它更新了Redux商店,基本上将用户添加到状态中。还有一个logout
按钮。注销后,它重定向到主页,操作和reducer清除Redux状态并从localStorage中删除令牌。
如果我在加载配置文件之前转到我的配置文件页面并注销,那么即使我已经单击了logout
按钮,props.profile()
仍然会加载。就像这张照片一样。
我认为我的useEffect
有问题,因为单击logout
按钮时组件没有卸载。
useEffect(() => {
props.profile();
return;
}, [props]);
还有一个return;
,但我不知道该怎么办。
所需结果:如果我单击登出,我希望卸载组件并清除状态。
注销操作:
export const logout = () => (dispatch) => {
localStorage.removeItem("token");
dispatch({
type: LOGOUT,
});
};
注销减速器:
case LOGOUT:
return {
user: {},
authenticated: false,
loading: false,
error: null,
token: null,
};
无论useEffect
中的return
如何,组件总是卸载。没有发生的是在卸载时调用了一些东西。
尝试将您的代码更改为以下内容:
useEffect(() => {
props.profile();
return () => props.logout(); //logout should be your redux action
}, [props.profile, props.logout]); // Reduce triggers of this method by not leaving `props` here