React v6-Redux创建私有路由

o2g1uqev  于 2022-11-12  发布在  React
关注(0)|答案(1)|浏览(160)

我试图创建一个PrivateRoutes除了常规的路线。登录后,页面被成功地重定向到/home,但当我试图打开/work,页面将返回到/home。所有的数据从状态。有效的是也显示“未识别”在/work。
我发现在privateRoutes中它会检查valid.isAuthenticated是否为true。但是由于. valid.isAuthenticated在reducer中被设置为false作为初始值,所以每次我打开/home或/work时,它都会重新呈现/login,然后再呈现/home或/work。
如何修复在打开其他页面之前不呈现/登录的问题?
这里是我的PrivateRoutes.js

import React from "react";
import { useSelector } from "react-redux";
import { Navigate } from "react-router-dom";

const PrivateRoute = ({ children }) => {
  const valid = useSelector((state) => state.valid);
  return valid.isAuthenticated ? children : <Navigate to="/login" />;
};

export default PrivateRoute;

这是我的AppRouter. js
第一个

ijxebb2r

ijxebb2r1#

import React from "react";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import PrivateRoute from "./PrivateRoute";

import App from "../components/App";
import Login from "../components/Login";
import HomePage from "../components/HomePage";
import WorkPage from "../components/WorkPage";

const AppRouter = () => {
    useEffect(() => {
        if (!valid.isAuthenticated) {
            navigate("/login");
        }
    });

    return (
        <BrowserRouter>
            <div>
                <NavigationBar />
                <div>
                    {valid.isAuthenticated ? <>
                        <Routes>
                            <Route path="/" element={<App />} exact />
                            <Route path="/home" element={<HomePage />} />
                            <Route path="/work" element={<WorkPage />} />
                        </Routes>
                    </>
                        :
                        <>
                    <Routes>
                            <Route path="/login" element={<Login />} exact />
                    </Routes>
                        </>
                    }
                </div>
            </div>
        </BrowserRouter>
    )

};
export default AppRouter;

相关问题