我通过创建一个保护页面来实现路由保护,每当用户未登录时,我都会将其包装在要保护的页面中,但是如果用户登录了,他/她就会返回到登录页面,我想知道什么我的保护页面丢失了。以下是我在 Protect.js 中实现的内容:
import { useRouter } from 'next/router'
import React, { useEffect,useState } from 'react'
import {useUser} from "src/contexts/useUser"
import { supabase } from 'src/db/supabase'
const Protect = ({children}) => {
// const {user,isLoading} = useUser()
const {auth,isauth}=supabase.auth.getSession()
const{user,isLoading}=supabase.auth.getUser()
const [authenticatedState, setAuthenticatedState] = useState('not-authenticated')
const Router = useRouter()
useEffect(()=>{
if(!isLoading && !user){
Router.replace('/auth/login')
}
},[isLoading,user,Router,auth,isauth])
return (
<> {children}>
)
}
export default Protect
下面是我的受保护页面:
import Head from 'next/head';
import { subDays, subHours } from 'date-fns';
import { Box, Container, Unstable_Grid2 as Grid } from '@mui/material';
import { Layout as DashboardLayout } from 'src/layouts/dashboard/layout';
import { OverviewBudget } from 'src/sections/overview/overview-budget';
import { OverviewLatestOrders } from 'src/sections/overview/overview-latest-orders';
import { OverviewLatestProducts } from 'src/sections/overview/overview-latest-products';
import { OverviewSales } from 'src/sections/overview/overview-sales';
import { OverviewTasksProgress } from 'src/sections/overview/overview-tasks-progress';
import { OverviewTotalCustomers } from 'src/sections/overview/overview-total-customers';
import { OverviewTotalProfit } from 'src/sections/overview/overview-total-profit';
import { OverviewTraffic } from 'src/sections/overview/overview-traffic';
// import {useUser} from 'src/contexts/user'
import { useRouter } from 'next/router';
import { useEffect } from 'react';
import Protect from 'src/contexts/Protect';
import { supabase } from 'src/db/supabase';
const now = new Date();
const Page = () => {
const router = useRouter()
// const user = useUser()
useEffect(()=>{
const user = supabase.auth.getUser()
if(!user){
router.push('/auth/login')
}
})
return(
<>
>
)
};
Page.getLayout = (page) => (
{page}
);
export default Page;
我尝试使用supabase中的getUser()钩子从supabase获取用户,但它不起作用
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
.getUser()是一个异步方法,所以你必须使用await来获取值,它只返回data和error对象,所以没有user或isLoading。const { data, error } = await supabase.auth.getUser()您可以在
useEffect中调用.getUser(),如果data为空,则将用户路由到登录页面。