繁体   English   中英

React Router Dom,受保护路由,获取ProtectedRoute不是路由

[英]React Router Dom, protected route, getting ProtectedRoute is not a route

我在我的应用程序中创建了文件 auth.js 文件和 ProtectedRoute.js。 在 API 中使用 JWT 创建一个令牌并在登录我的应用程序时存储在本地存储中。 在我的 app.js 中导入了 Authprovider 和 ProtectedRoute,它在路由中显示错误。请检查我的代码并告诉我哪里出错了

auth.js

  import { useContext, createContext } from "react";

  const AuthContext = createContext(null)

  export const AuthProvider=({ children })=>{

  const keyToken = localStorage.getItem("token");
  const user = localStorage.getItem("name");
  const userid = localStorage.getItem("id");
  const pimg = localStorage.getItem("profile");

  return(
         <AuthContext.Provider value={{ keyToken,user,userid,pimg}}> {children} 
         </AuthContext.Provider>
      )
    } 

   export const useAuth = () => {
           return useContext(AuthContext)
     }

protectedRoute.js

import React from "react";
import { Navigate , Route } from "react-router-dom";
import {useAuth} from "./auth"

function ProtectedRoute({ component: Component, ...restOfProps }) {

  const auth=useAuth();
  const isAuthenticated = auth.keyToken;
  console.log("this", isAuthenticated);
 

  return (
    <Route
      {...restOfProps}
      render={(props) =>
        false ? <Component {...props} /> : <Navigate  to="/login" />
      }
    />
  );
}

export default ProtectedRoute;

应用程序.js

import React from "react";
import ReactDOM from "react-dom";
import {BrowserRouter as Router,Routes,Route} from 'react-router-dom';
import Login from "./components/SignIn";
import Category from "./pages/Category";
import Addcategory from "./pages/Addcategory";
import Subcategory from "./pages/Subcategory";
import Dashboard from "./pages/Dashboard";
import { Profile } from "./components/Profile";
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { AuthProvider} from "./components/authentication/auth";
import ProtectedRoute from "./components/authentication/protectedRoute";

function App() {
  return (
    <AuthProvider>
    <Router>
      <Routes>
          <Route exact path='/' element={< Login />}></Route>
          <Route exact path='/login' element={< Login />}></Route>
         <ProtectedRoute exact path='/dashboard' element={ Dashboard}/>
         {/*<Route exact path='/dashboard' element={< Dashboard />}></Route>*/}
          <Route exact path='/category' element={< Category />}></Route>
          <Route exact path='/categoryAdd' element={< Addcategory />}></Route>
          <Route exact path='/subcategory' element={< Subcategory />}></Route>
         <Route exact path='/profile' element={< Profile />}></Route> 
      </Routes>
      <ToastContainer />
    </Router>
    </AuthProvider>
  );
}
ReactDOM.render(<App />, document.getElementById("root"));

export default App;

控制台中显示错误:

在此处输入图像描述

虽然你为ProtectedRoute所做的我认为适用于 React Router Dom 版本 5,但版本 6 略有不同。 这是一种方法(查看图书馆团队制作的这个示例以了解更多信息):

应用程序.js:

function App() {
  return (
    <AuthProvider>
    <Router>
      <Routes>
          <Route exact path='/dashboard' element={ <ProtectedRoute/>}/>
      </Routes>
      <ToastContainer />
    </Router>
    </AuthProvider>
  );
}

保护路由.js:

function ProtectedRoute() {

  const auth=useAuth();
  const isAuthenticated = auth.keyToken;

  if(isAuthenticated){
    return <Dashboard/>
  }
  return (
    <Navigate  to="/login" />
   );
}

export default ProtectedRoute;

您混合了react-router-dom v5v6的代码,您可以阅读从 v5 升级的迁移指南

可以使用OutletProtectedRoute渲染为布局。 检查这个例子

// ProtectedRoute.js
import { Navigate, Outlet } from 'react-router-dom';

export const ProtectedRoute = () => {
  const location = useLocation();
  const auth = useAuth();

  return auth.isAuthenticated
    ? <Outlet />
    : <Navigate to="/login" state={{ from: location }} replace />;
};

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

function App() {
  return (
    <AuthProvider>
      <BrowserRouter>
        <Routes>
          <Route path="/login" element={<Login />} />
          <Route path="/" element={<ProtectedRoute /> }>
            <Route path='dashboard' element={<Dashboard />} />
            <Route path='category' element={<Category />} />
            // rest of your code
          </Route>
        </Routes>
        <ToastContainer />
      </BrowserRouter>
    </AuthProvider>
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM