受保护的路由检查用户 api

Protected routes check user api

我正在尝试检查受保护的路由器。现在我想为每个检查用户调用我的 api。我试了一下,但没有用。这是我的代码。我的react版本是17,react-router-dom 6。我也用typescript。

我的App.tsx

  <Routes>
        <Route>
          <Route path="/" element={<Login />} />
          <Route path="/login" element={<Login />} />
          <Route element={<ProtectedRoutes />}>
              <Route path="/dashboard" element={<Dashboard />} />
          </Route>
        </Route>
      </Routes>

接下来这是我的 ProtectedRoutes 包装器

import { Navigate, Outlet } from "react-router-dom";

const AuthWrapper = () => {

    if (window.sessionStorage.getItem('jwt')) {
        /* =============== HERE CALL MY API CHECK =============== */
        return  <Outlet /> 
    }
     else 
    {
      return  <Navigate to="/login" replace />
    }

  };

export default AuthWrapper;

现在……问题是……当我从会话存储中获取 jwt 时,我想调用我的每次检查 jwt 等待,然后 return 或导航到登录 有人可以帮助我吗?非常感谢

应该使用 useEffect 挂钩来访问 JWT 令牌和 运行 异步身份验证检查。使用不确定的身份验证状态有条件地 return 提前为空或加载指示器,并且仅在身份验证检查完成后才允许呈现路由组件或重定向。

示例:

const AuthWrapper = () => {
  const location = useLocation();
  const [auth, setAuth] = useState();
  const [isLoading, setIsLoading] = useState(true);

  useLayoutEffect(() => {
    const authCheck = async () => {
      setIsLoading(true);
      const JWT = JSON.parse(window.sessionStorage.getItem("jwt"));

      if (!JWT) {
        setAuth(false); // or unauthorized value
        return;
      }

      try {
        /* =============== HERE CALL MY API CHECK =============== */

        // await the asynchronous logic
        const auth = await .....

        setAuth(auth);
      } catch (error) {
        // handle any Promise rejections, errors, etc...
        setAuth(false); // or unauthorized value
      } finally {
        setIsLoading(false);
      }
    };

    authCheck();

    return () => {
      // cancel/clean up any pending/in-flight asynchronous auth checks
    };
  }, [location.pathname]); // <-- check authentication when route changes

  if (isLoading) {
    return null; // or loading spinner, etc...
  }

  return auth // or auth property if object, i.e. auth.isAuthenticated, etc...
    ? <Outlet />
    : <Navigate to="/login" replace />;
};