【问题标题】:React useEffect and componentWillUnmount with Redux使用 Redux 反应 useEffect 和 componentWillUnmount
【发布时间】:2020-08-05 14:01:17
【问题描述】:

有一个个人资料页面。每次我访问我的个人资料时,这里都会加载props.profile()。它更新 Redux 存储并基本上将用户添加到状态。还有一个logout 按钮。注销后重定向到主页,action 和 reducer 清除 Redux 状态并从 localStorage 中删除令牌。

如果我转到我的个人资料页面并在加载个人资料之前退出,那么即使我已经点击了logout 按钮,props.profile() 仍然会加载。喜欢in this image

我认为我的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,
            };

【问题讨论】:

  • useEffectreturn 函数将用于任何清理 - reactjs.org/docs/hooks-effect.html#effects-with-cleanup
  • 只要你转到profile page,它就会调用useEffect,而且它的操作非常快,我认为你不能在它被调用之前注销。
  • 我将logout 按钮放在配置文件页面上用于测试目的,我可以在props.profile() 运行之前快速单击它。然后它让我退出,但props.profile() 仍然在后面运行。

标签: javascript reactjs redux


【解决方案1】:

无论您的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

【讨论】:

  • 问题依然存在。我转到我的个人资料页面,它会加载我的个人资料页面,但是如果我在加载props.profile() 之前单击logout 按钮,那么即使在注销后,它也会加载配置文件并将数据放入 Redux 存储中。
  • @David 我已经对代码进行了一些更改,你能再试一次吗?
  • @David 如果您的页面是通过导航库挂载的,那么当您交换页面时,很有可能该页面实际上并没有被卸载。
  • 是的,我使用 react-router-dom 和 导航。因此,使用更新的代码:我在 /profile 但如果我去 /feed 然后它会自动将我注销。那么我应该如何卸载它呢?
  • 因为你有这个[props.profile, props.logout]。即使更改配置文件(prop.profile)也可能触发注销。
猜你喜欢
  • 1970-01-01
  • 2020-11-25
  • 2020-05-07
  • 2021-08-28
  • 2021-07-31
  • 2021-05-11
  • 1970-01-01
  • 1970-01-01
  • 2021-10-03
相关资源
最近更新 更多