我正在try 实现到我的应用程序的私有路由,虽然它在经过身份验证时正确地到达了私有路由,但它会将其重定向到登录页面,而不是子页面.我try 了堆栈溢出的所有解决方案,但似乎都不起作用.这很奇怪,因为它到达了正确的路径(每当我到达私有路由时,我都会打印到控制台),但它无法正确地重定向页面.

PrivateRouting专用路由

import { useState, useEffect } from 'react';
import { useRef } from 'react';
import { Outlet, Navigate, useLocation } from 'react-router-dom';
import Axios from "axios";
import Cookies from "universal-cookie";

export default function ProtectedRoute({ children }) {
  const [isAuthenticated, setIsAuthenticated] = useState();
  // add loading state, initially true for initial render
  const [isLoading, setIsLoading] = useState(true);
  const checkAuth = async () => {
    const cookie = new Cookies(); 
    setIsLoading(true); // <-- set true when starting auth check
    try {
      if (cookie.get("stytch_session") == null) {
        console.log("no cookies!")
        setIsAuthenticated(false);
      } else {
        Axios.post(
          "http://localhost:5001/test",
          {},
          { headers: { sessiontoken: cookie.get("stytch_session") } }
        )
          .then((response) => {
            console.log("reaching private route!")
            setIsAuthenticated(true);
          })
          .catch((err) => {
            console.log(err)
            setIsAuthenticated(false);
          });
      }
    } finally {
      setIsLoading(false); // <-- clear loading state when completed
    }
  };

  useEffect(() => {
    checkAuth();
  }, []);

  if (isLoading) {
    return <div className="">Loading...</div>;
  }

  return isAuthenticated ? children : <Navigate to={"/login"} />;

}

下面是在app.js中调用的代码片段

<Route
  path="/scroll"
  element={(
    <ProtectedRoute>
      <Scroll /> 
    </ProtectedRoute>
  }
/> 

推荐答案

axios.post启动了一个同步代码不会等待的异步promise 链.finally块在POST请求解析之前执行.

代码应该是await的promise 来解析.

export default function ProtectedRoute() {
  const [isAuthenticated, setIsAuthenticated] = useState();

  // add loading state, initially true for initial render
  const [isLoading, setIsLoading] = useState(true);

  const checkAuth = async () => {
    const cookie = new Cookies(); 
    setIsLoading(true);

    try {
      if (cookie.get("stytch_session") == null) {
        console.log("no cookies!")
        setIsAuthenticated(false);
      } else {
        await Axios.post(
          "http://localhost:5001/test",
          {},
          { headers: { sessiontoken: cookie.get("stytch_session") } }
        );
        console.log("reaching private route!")
        setIsAuthenticated(true);
    } catch(err) {
      console.log(err);
      setIsAuthenticated(false);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    checkAuth();
  }, []);

  if (isLoading) {
    return <div className="">Loading...</div>;
  }

  return isAuthenticated ? <Outlet /> : <Navigate to="/login" replace />;
}
<Route element={<ProtectedRoute />}>
  <Route path="/scroll" element={<Scroll />} />
  ... other protected routes ...
</Route>

Javascript相关问答推荐

为什么我会获取MUI Date TimePicker TypHelp:Value.isValid不是AdapterDayjs.isValid中的函数

获取POS餐厅会话用户/收银员

如何在ReactJS中修复这种不需要的按钮行为?

React redux状态未在React-Router库中呈现

橡皮擦完全让画布变成白色

确定MutationRecord中removedNodes的索引

colored颜色 检测JS,平均图像 colored颜色 检测JS

如何添加绘图条形图图例单击角形事件

在react JS中映射数组对象的嵌套数据

在open shadow—root中匹配时,使用jQuery删除一个封闭的div类

如何迭代叔父元素的子HTML元素

不能将空字符串传递给cy.containes()

如何修复我的数据表,以使stateSave正常工作?

WP Bootstrap NavWaker:下拉菜单一次打开所有下拉菜单

SPAN不会在点击时关闭模式,尽管它们可以发送日志(log)等

一个实体一刀VS每个实体多刀S

MongoDB受困于太多的数据

使每个<;li>;元素的 colored颜色 与随机生成的 colored颜色 列表不同(不重复

将Auth0用户对象存储在nextjs类型脚本的Reaction上下文中

我正在试着做一个TicTacToe Ai来和我玩.但是,我试着在第一个方块被点击时出现一个X,然后在第二个方块之后出现一个O