无法通过useEffect

时间:2020-08-23 13:11:37

标签: javascript reactjs redux-thunk

我正在尝试将我的用户重定向到专用路由。我正在使用redux thunk通过storeUser()从数据库中获取用户信息,如果该信息存在,那么用户将继续进行操作,否则他们将被重定向回首页。但是它没有按预期工作。它应该继续时重定向到主页。我可以使用基于类的语法和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);

尽管如此,代码仍将始终重定向用户。即使props.user.email为true,isAuth也永远不会返回true。它可以运行并重定向,直到有机会运行handleIsAuth(true)

1 个答案:

答案 0 :(得分:1)

您有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,
    };
};