无法使用 useEffect 对未安装的组件问题执行反应状态更新

can't perform a react state update on an unmounted component issue with useEffect

我正在尝试将我的用户重定向到专用路由。我正在使用 redux thunk 从数据库中获取用户信息,使用 storeUser(),如果信息存在,则用户继续,否则他们将被重定向回主页。但是它没有按预期工作。它应该在应该继续的时候重定向回主页。我可以使用基于 class 的语法和 componentDidMount 来做到这一点。我试图通过使用 authChecked 状态来确定组件何时完成渲染来解决无法访问 componentDidMount 的问题

const PrivateRoute = (props) => {
    const [authChecked, handleAuthChecked] = useState(false);
    const [isAuth, handleIsAuth] = useState(false);

    useEffect(() => {
        props
            .storeUser()
            .then(() => {
                props.user.email ? handleIsAuth(true) : handleIsAuth(false);
                handleAuthChecked(true);
            })
            .catch(() => {
                handleAuthChecked(true);
            });
    }, [props]);

    if (authChecked) {
        return isAuth ? <props.component /> : <Redirect to="/" />;
    }
    return null;
};

const mapStateToProps = (state) => {
    return {
        user: state.user,
    };
};

export default connect(mapStateToProps, { storeUser })(PrivateRoute);

代码将始终重定向用户。 isAuth 永远不会 return 为真,即使 props.user.email 为真。它 运行 在它有机会 运行 handleIsAuth(true)

之前重定向

您有 2 个问题可能导致您看到的缺陷:

  1. 第一个问题是由 useEffect 内的函数作用域和您对 storeUser 的回调引起的。不要依赖回调来确定用户是否有电子邮件地址,只需在您的渲染条件下执行此操作,让 redux + react 渲染周期帮助您。
  2. 此外,您应该只在挂载时调用 storeUser 操作。不是每次 props 更新。

例如:

const PrivateRoute = (props) => {
    const [authChecked, handleAuthChecked] = useState(false);

    useEffect(() => {
        props
            .storeUser()
            .then(() => {
                handleAuthChecked(true);
            })
            .catch(() => {
                handleAuthChecked(true);
            });
    }, []);

    if (authChecked) {
        return !!props.user.email 
          ? <props.component /> 
          : <Redirect to="/" />;
    }
    
    return null;
};

const mapStateToProps = (state) => {
    return {
        user: state.user,
    };
};