我有一个firebase onAuthStateChange和一组私有路由要用react router v6呈现
useEffect(() => {
const fetchData = async () =>
await auth.onAuthStateChanged(async authUser => {
console.log('here in authuser')
if (authUser) {
await dispatch(setUser('SET_USER', authUser))
} else {
await dispatch(setUser('SET_USER', null))
}
})
fetchData()
}, [])
<Route path='/' element={<PrivateRoute user={users} />}>
<Route path='/courses/:id' element={<CourseDetails />} />
<Route
path='/'
element={<Courses emailId={users?.user?.email} />}
/>
<Route path='/enrolled' element={<Enrolled />} />
<Route path='/authored' element={<Authored />} />
<Route path='/users' element={<Users />} />
</Route>
在受保护的路由组件中,我检查用户是否为空,然后将用户重定向到登录页面,否则渲染子节点。
if (user === null || user.user === null) {
console.log('Entered!!!!!')
return <Navigate to='/login' replace />
} else {
return children ? children : <Outlet />
}
在页面刷新时,如果我登录了,我也被重定向到登录路由,因为onauthstatechange还没有完成执行。所以user在
里面是空的处理这种情况的正确方法是什么,并确保用户导航到发生重新加载的同一页面。
您可以创建一个组件来为您处理检查。
在你的路由中,你把PrivateRoute
包在你的路由组件中,像这样:
<Route path='/courses/:id' element={<PrivateRoute><CourseDetails /></PrivateRoute> } />
这个组件的作用是检查用户是否是authed
。如果是authed
,它将渲染子组件,也就是你的路由。如果不是,它将重定向到/login
他们在文档中谈论它
const PrivateRoute =({ children }: { children: JSX.Element }) => {
let auth = useAuth();
let location = useLocation();
if (!auth.user) {
// Redirect them to the /login page, but save the current location they were
// trying to go to when they were redirected. This allows us to send them
// along to that page after they login, which is a nicer user experience
// than dropping them off on the home page.
return <Navigate to="/login" state={{ from: location }} replace />;
}
return children;
}