如何在React组件中使用Firebase保留验证状态

发布于 2025-01-26 20:14:39 字数 1359 浏览 4 评论 0原文

我有一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

静谧 2025-02-02 20:14:39

您可以创建一个为您处理支票的组件。

因此,在您的路线中,您将Privateroute与您的路由组件包装:

<Route path='/courses/:id' element={<PrivateRoute><CourseDetails /></PrivateRoute> } />

因此,该组件的作用是检查用户是否是eulteded。如果是授权,它将渲染您的路由的子组件。如果不是,它将将您重定向到/login

他们在 docs

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;
}

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 :

<Route path='/courses/:id' element={<PrivateRoute><CourseDetails /></PrivateRoute> } />

So what this component does is check if the user is authed. If it is authed 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

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文