重新加载私有路由页面后,用户将被重定向到登录页面。 [反应路由器]

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

我使用反应路由器创建了一条受保护的路由进行身份验证。登录/注册后,它将用户重定向到博客页面。但是当我刷新博客页面时,我需要再次登录页面。我想在刷新后留在博客页面上。我该怎么做呢? 我使用了 React router hooks、firebase、react bootstrap

<Route
   path="/blogs"
   element={
   <RequireAuth>
     <Blogs></Blogs>
   </RequireAuth>
   }
></Route>

需要验证文件 -

import React from "react";
import { useAuthState } from "react-firebase-hooks/auth";
import { Navigate, useLocation } from "react-router-dom";
import auth from "../../firebase.init";

function RequireAuth({ children }) {
  const [user] = useAuthState(auth);
  let location = useLocation();

  if (!user) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  return children;
}

export default RequireAuth;

登录页面-

import { Link, useLocation, useNavigate } from "react-router-dom";

const Login = () => {
  let navigate = useNavigate();
  let location = useLocation();
  let from = location.state?.from?.pathname || "/";


  const handleSubmit = async (event) => {
    // firebase login code
    navigate(from, { replace: true });
  };

  return (
      <Form onSubmit={handleSubmit}>
        
      </Form>
  );
};

export default Login;
reactjs firebase react-router
1个回答
0
投票

您可以将导航用户到他原本想要访问的上一页的部分放在 useEffect 中,而不是放在 handleSubmit 函数中

useEffect(() => {
    if (user) {
      navigate(from);
    }
  }, [from, navigate, user]);

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