【问题标题】:How to perform authentication with React hooks and react-router如何使用 React hooks 和 react-router 执行身份验证
【发布时间】:2019-08-16 22:31:10
【问题描述】:

我正在尝试使用react-router-domreact hooks 在每次路由更改时对用户进行身份验证。 这个想法是,每次用户导航到路线时,系统都会进行 api 调用并对用户进行身份验证。 我需要实现这一点,因为我使用react-redux,并且在每个窗口重新加载时,redux 状态都不会持久化。所以我需要再次将isLoggedNow 属性设置为true

const PrivateRoute = ({
  component: Component,
  checkOnEachRoute: checkReq,
  isUserLogged,
  ...rest
}) => {
  const [isLoggedNow, setLogged] = useState(isUserLogged);
  useEffect(
    () => {
      const fetchStatus = async () => {
        try {
          await selectisUserLogged();
          setLogged(true);
        } catch (error) {
          console.log(error);
        }
      };
      fetchStatus();
    },
    [isUserLogged],
  );
  return (
    <Route
      {...rest}
      render={props =>
        isLoggedNow ? (
          <div>
            <Component {...props} />
          </div>
        ) : (
          <Redirect
            to={{
              pathname: '/login',
            }}
          />
        )
      }
    />
  );
};

然后我会像这样使用上面的PrivateRoute

function App(props) {
  return (
    <div>
      <Switch location={props.location}>
        <Route exact path="/login" component={Login} />
        <PrivateRoute exact path="/sidebar" component={Sidebar} />
      </Switch>
    </div>
  );
}

首先isUserLoggedtrue,但在重新加载窗口后我收到错误Warning: Can't perform a React state update on an unmounted component. 那么我该如何实现这一点,所以在每次重新加载窗口时我都会对用户进行身份验证?我正在寻找某种componentWillMount

【问题讨论】:

  • 您有机会解决这个问题吗?
  • @camelCase 是的!
  • 愿意分享吗? :) 目前面临完全相同的问题
  • @camelCase 看看我的回答,它为你解决了吗?:)

标签: javascript reactjs react-hooks


【解决方案1】:

类似这样的工作(其中isUserLogged 是来自redux 的道具):

function PrivateRoute({ component: Component, isUserLogged, ...rest }) {
  const [isLoading, setLoading] = useState(true);
  const [isAuthenticated, setAuth] = useState(false);
  useEffect(() => {
    const fetchLogged = async () => {
      try {
        setLoading(true);
        const url = new URL(fetchUrl);
        const fetchedUrl = await fetchApi(url);
        setAuth(fetchedUrl.body.isAllowed);
        setLoading(false);
      } catch (error) {
        setLoading(false);
      }
    };
    fetchLogged();
  }, []);
  return (
    <Route
      {...rest}
      render={props =>
        // eslint-disable-next-line no-nested-ternary
        isUserLogged || isAuthenticated ? (
          <Component {...props} />
        ) : isLoading ? (
          <Spin size="large" />
        ) : (
          <Redirect
            to={{
              pathname: '/login',
            }}
          />
        )
      }
    />
  );
}

【讨论】:

  • 似乎也为我工作,只是有一个问题,为什么你有 isUserLogged 传入的道具?
  • @camelCase 我有一个想法将fetchLogged(); 包装在ìf(!isUserLogged)... 中,所以只有在不是isUserLogged 时才获取:)
猜你喜欢
  • 1970-01-01
  • 2018-05-17
  • 2020-12-23
  • 2020-05-28
  • 2020-08-26
  • 2018-07-31
  • 2019-04-11
  • 2019-03-05
相关资源
最近更新 更多