【问题标题】:How to correctly redirect user after authentication?认证后如何正确重定向用户?
【发布时间】:2020-08-26 10:00:27
【问题描述】:

我正在使用react-redux,目前我的全局状态中有一个布尔型isAuthenticated 属性,如果这是真的,它将重定向到/home 组件。

我实施的方法有更好的方法吗?如何解决输出错误?

import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { login } from "./actions";
import { useHistory } from "react-router-dom"

const Login = () => {
  const dispatch = useDispatch();
  const history = useHistory();
  const myState = useSelector(
    state => state.authentication
  );

  const onSubmit = (values) => {
    dispatch(login(values.email, values.password));
  };

  useEffect(() => {
    if (myState.isAuthenticated) {
      history.push("/home")
    }
  }, [isAuthenticated]);

}

警告:React Hook useEffect 缺少依赖项:'history'。要么包含它,要么移除依赖数组

[isAuthenticated, history]这可以接受吗?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    我实施的方法有更好的方法吗?如何解决输出错误?

    答案取决于您将逻辑保存在何处。如果您将所有逻辑都保留在组件的状态中,那么useEffect 方式非常好。

    要解决警告,只需将历史记录放入 useEffect 输入,如下所示:

    useEffect(() => {
        if (myState.isAuthenticated) {
          history.push("/home")
        }
      }, [myState.isAuthenticated, history]);
    

    现在每次对历史对象的引用发生变化时都会触发 useEffect。如果你使用 React Router,那么 history 实例很可能是可变的,它不会改变,因此不会触发 useEffect。所以将它包含在 UseEffect 依赖数组中应该是安全的。

    【讨论】:

    • 这就是我为解决这个问题所做的,但我认为会有更好的方法,因为我还是新的 useEffect。谢谢:)
    【解决方案2】:

    更好的方法是始终创建单独的 PrivateRoute 组件来处理您的身份验证。如果您浏览 react router 官方文档,他们已经给出了一个很好的身份验证示例:

    function PrivateRoute({ children, ...rest }) {
      const myState = useSelector(
        state => state.authentication
      );
      return (
        <Route
          {...rest}
          render={({ location }) =>
            myState.isAuthenticated ? (
              children
            ) : (
              <Redirect
                to={{
                  pathname: "/login",
                  state: { from: location }
                }}
              />
            )
          }
        />
      );
    }
    
    

    你可以像这样在层中使用它:

    <Switch>
              <Route path="/public">
                <PublicPage />
              </Route>
              <Route path="/login">
                <LoginPage />
              </Route>
              <PrivateRoute path="/protected">
                <ProtectedPage />
              </PrivateRoute>
            </Switch>
    

    这样您就不必手动跟踪您的身份验证。 这是来自 react-router 网站的完整演示:https://reactrouter.com/web/example/auth-workflow

    【讨论】:

      猜你喜欢
      • 2013-10-14
      • 2021-12-31
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 2018-04-19
      • 1970-01-01
      • 2012-09-24
      • 2020-02-26
      相关资源
      最近更新 更多