保护路由后,虽然登录成功,但还是卡在了登录页面

问题描述 投票:0回答:1

我正在使用

<ProtectedRoutes/>
保护我的路由,场景是在成功登录后导航用户到
/dashboard
,问题是无论我成功登录多少次,浏览器的URL都会更改为
/dashboard
不到一秒钟,然后再次返回
/login
页面。我从supabase获取了包含经过身份验证的用户的所有信息的对象。

这是我的路线,我小时候制作的所有路线都到了

<ProtectedRoutes/>

const router = createBrowserRouter([
  {
    element: <ProtectedRoutes/>,
    children: [
      {
        element: <AppLayouts />,
        children: [
          {
            path: "/",
            element: <Navigate to="/dashboard" replace />,
          },
          {
            path: "/dashboard",
            element: <Dashboard />,
          },
          {
            path: "/users",
            element: <NewUsers />,
          },
          {
            path: "/account",
            element: <Account />,
          },
          {
            path: "/bookings",
            element: <Bookings />,
          },
          {
            path: "/bookings/:id",
            element: <OneBookingDetails/>,
          },
          {
            path: "/checkin/:id",
            element: <Checkin/>,
          },
          {
            path: "/cabins",
            element: <Cabins />,
          },
          {
            path: "/settings",
            element: <Settings />,
          },
        ],
      },
      ]
  },
 
  {
    path: "/login",
    element: <Login />,
  },
  {
    path: "*",
    element: <PageNotFound />,
  },
]);

受保护的路线:

export default function ProtectedRoutes({children}) {
    const navigate = useNavigate();
    
    // 1) load the authenticated User:
    const {isAuthenticated, isLoading} = useUser();
    useEffect(function(){
        // 3) not an authenticaed user? then redirect to the login page
        if(!isAuthenticated && !isLoading) navigate("/login");
    }, [isAuthenticated, isLoading, navigate]);

    // 2) show a spinner while the process of checking is taking place:
    if(isLoading) return <SpinnerContainer><Spinner/></SpinnerContainer>


    // 4) an authenticated user? render the app (children):
    if(isAuthenticated) return children;
}

使用用户钩子:

    import { useQuery } from "@tanstack/react-query";

import { getCurrentUser } from "../../services/apiAuth";

    export async function useUser() {
        const {isLoading, data: user, fetchStatus} = useQuery({
            queryKey: ["user"],
            queryFn: getCurrentUser
        });
    
        return {isLoading, fetchStatus, user, isAuthenticated: user?.role === "authenticated"};
    }

useLogin 挂钩,负责导航到

/dashboard
(请注意,每次登录过程后我都会得到
toast.success("Welcome Back!");

import { useMutation } from "@tanstack/react-query";
import { login as loginApi } from "../../services/apiAuth";
import { useNavigate } from "react-router-dom";
import toast from "react-hot-toast";

export function useLogin() {
    const navigate = useNavigate();
    const {isLoading: isLogging, mutate: login} = useMutation({
        mutationFn: ({email, password}) => loginApi({email, password}),
        onSuccess: () => {
            toast.success("Welcome Back!");
            navigate("/dashboard");
        },
        onError: (error) => {
            console.log(error.message);
            toast.error("something went wrong, pleast try to login again.")
        }
    });

    return {isLogging, login}
}

更新:

  • user
    内打印
    useEffect()
    对象是
    undefined
    ,但它不在
    userUser()

  • 当我删除此条件后

    if(!isAuthenticated && !isLoading) navigate("/login");
    我被重定向到
    /dashboard
    但什么也没有出现,页面是白色的,这与所有其他页面的情况相同

reactjs react-router supabase react-query
1个回答
0
投票

我的问题在于两件事:

  • 第一个:

    async
    钩子中的
    useUser
    关键字,现已删除

  • 第二:我将路由器实现更改为如下:

    const 路由器 = createBrowserRouter([ { 元素: , 孩子们: [ { // 索引路由 - 这是我们打开应用程序后首先希望看到的内容。 小路: ”/”, 元素: , }, { 路径:“/仪表板”, 元素: , }, { 路径:“/用户”, 元素: , }, { 路径:“/帐户”, 元素: , }, { 路径:“/预订”, 元素: , }, { 路径:“/预订/:id”, 元素: , }, { 路径:“/签入/:id”, 元素: , }, { 路径:“/小屋”, 元素: , }, { 路径:“/设置”, 元素: , }, ], },

    {
      path: "/login",
      element: <Login />,
    },
    {
      path: "*",
      element: <PageNotFound />,
    },
    

    ]);

现在一切正常。

© www.soinside.com 2019 - 2024. All rights reserved.