如何在React组件中使用Firebase保留验证状态
我有一个firebase onauthstatechange和一组私人路由,可以
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>
在受保护的路由组件中使用React Router V6渲染的私人路线,我正在检查用户是否为null,然后重定向用户登录页面,以其他求孩子。
if (user === null || user.user === null) {
console.log('Entered!!!!!')
return <Navigate to='/login' replace />
} else {
return children ? children : <Outlet />
}
在刷新页面上,如果我还登录,我也将重定向到登录路线,因为Onauthstatechange尚未完成执行。因此,用户在
处理这种情况的正确方法中是无效的,并确保用户被导航到重新加载的同一页面。
I have a firebase onAuthStateChange and a set of private routes to be rendered with 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>
In the protected route component I am checking if user is null then redirect user to login page else render the children.
if (user === null || user.user === null) {
console.log('Entered!!!!!')
return <Navigate to='/login' replace />
} else {
return children ? children : <Outlet />
}
On page refresh if I am logged in also I am redirected to login route because onauthstatechange has not finished executing. So user is null inside the
What is the right way to handle this situation and make sure that user gets navigated to the same page where reload happened.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以创建一个为您处理支票的组件。
因此,在您的路线中,您将
Privateroute
与您的路由组件包装:因此,该组件的作用是检查用户是否是
eulteded
。如果是授权
,它将渲染您的路由的子组件。如果不是,它将将您重定向到/login
他们在 docs
You can create a component that handles the check for you.
So in your route you wrap your
PrivateRoute
with your route component like this :So what this component does is check if the user is
authed
. If it isauthed
it will render the child component that is your route. If not it will redirect you to/login
they are talking about it in the docs