【问题标题】:Route Guard Doesn't work on first attempt with React and AmplifyRoute Guard 在第一次尝试使用 React 和 Amplify 时不起作用
【发布时间】:2022-01-10 03:12:16
【问题描述】:

我已经使用我的 React/Ionic 应用程序设置了路由保护,并且不希望在没有登录用户的情况下访问任何路由。但是,异步似乎工作不正常,因为当用户第一次尝试登录时它不会将用户导航到新路由,就像在评估登录之前函数返回一样。当您再次单击时,它似乎可以正常工作,并且可以正确导航。我该如何纠正这个问题?

import React, { useContext, useEffect, useState } from "react";
import { Route, Redirect } from "react-router-dom";
import { Auth } from "aws-amplify";

const PrivateRoute = ({ component: Component, restricted, ...rest }: any) => {
  const [userInfo, setAuth] = useState(false);
  const isAuthenticated = () => {
    Auth.currentSession()
      .then((response) => {
        if (response.isValid()) {
          setAuth(true);
        } else {
          setAuth(false);
        }
      })
      .catch(() => {      });
  };
  useEffect(() => {
    isAuthenticated();
  }, []);
  return (
    <Route
      {...rest}
      render={(props) =>
        userInfo ? <Component {...props} /> : <Redirect to="/login" />
      }
    />
  );
};

export default PrivateRoute;

这是我如何使用私人路线

<Route path="/login" component={Login} />
<PrivateRoute path="/verification" component={MainNavigtion} />

【问题讨论】:

    标签: reactjs typescript navigation aws-amplify


    【解决方案1】:

    userInfo 的初始值为 false,因此它会立即重定向到 /login

    尝试将userInfo默认值设置为null

    const [userInfo, setAuth] = useState(null);

    <Route
      {...rest}
      render={(props) =>
        userInfo === null ? <p>loading</p> : userInfo 
          ? <Component {...props} /> : <Redirect to="/login" />   
      }
    />
    

    我建议使用 Loader 组件包装您的 Route 组件,以便当 userInfo 为 null 时,它将显示 Loader。

    
    return (
        <Loader loading={userInfo===null}>
          <Route
            {...rest}
            render={(props) =>
              userInfo ? <Component {...props} /> : <Redirect to="/login" />
            }
          />
        </Loader>
      );
    

    【讨论】:

      猜你喜欢
      • 2016-10-17
      • 2021-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 1970-01-01
      • 2017-09-28
      相关资源
      最近更新 更多