簡體   English   中英

React-router-dom 受保護的路由不起作用

[英]React-router-dom Protected Routes are not working

受保護的 Routes.js:

在受保護的路由中,您可以看到我在 if 語句中直接使用 false 但我仍然能夠看到該頁面,為什么?

import React from 'react';
import { Route } from 'react-router-dom';
// import Auth from './User/Auth';
import Error401 from './Error/401';


// create a component for protected route


console.log('Routes.js');


export const ProtectedRoute = ({ element: Element, ...rest }) => {
    console.log("Function Called")
    return (
        <Route {...rest} render={props => {
                if(false){ 
                    return <Element {...props} />
                }else{
                    return <Error401 />
                }
            }
        } />
    )
}

App.js:這是我在其中使用受保護路由組件的 app.js

import './App.css';
import React from 'react';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import { Layout } from 'antd';
import { MoneyCollectOutlined } from '@ant-design/icons';
import Login from './Components/User/Login'; 
import Signup from './Components/User/Signup';
import {ProtectedRoute} from './Components/Routes';
import Error404 from './Components/Error/404';

function App() {
  return (
    <BrowserRouter>
      <Layout style={{minHeight:"100vh"}}>
        <Layout.Header>
          <h1 style={{color:"white"}} align="center"> <MoneyCollectOutlined/>MoneyG</h1>
        </Layout.Header>
        
        <Layout.Content style={{minHeight:"100%"}}>
          <Routes>
            <ProtectedRoute exact path="/register" element={<Signup/>} />
            <ProtectedRoute exact path="/login" element={<Login/>} />
            <Route path="*" element={<Error404/>} />
          </Routes>
        </Layout.Content>
        
      </Layout>
    
    </BrowserRouter>
  );
}

export default App;

首先, <Routes>元素應該只有<Route>元素作為子元素。 您應該將保護邏輯向下移動一層。

其次, render道具在 V6 中不再存在。 它被替換為element 請參閱文檔

以下是您可以解決的方法:

<Routes>
  <Route exact path="/register" element={(
    <ProtectedRoute>
      <Signup/>
    </ProtectedRoute>
  )} />
  <Route exact path="/login" element={(
    <ProtectedRoute>
      <Login/>
    </ProtectedRoute>
  )} />
  <Route path="*" element={<Error404/>} />
</Routes>

和:

const ProtectedRoute = () => {
  if (condition) { return <Error401 />; } // You might as well use Navigate here

  return children;
};

您可以使用 createContext 和 useContext

//store/AuthApi.jsx
import { createContext } from "react";
const AuthApi = createContext();
export default AuthApi;

然后定義上下文app.jsx

import React, from 'react'
import { AllRoutes } from 'routes/Routes';
import { BrowserRouter as Router } from "react-router-dom";
import AuthApi from 'store/AuthApi';
const App = () => {
  const [user, setUser] = useState(false);
  useEffect(() => {
     // you can get user from localStorage or Cookie(js-cookie npm)
     //then you can change user state true or false
  }, [])
  return (
    <>
      <AuthApi.Provider value={{ user, setUser }}>
        <Router>
          <AllRoutes />
        </Router>
      </AuthApi.Provider>
      <Toast />
    </>
  )
}

export default App

然后查看 AllRoutes

//routes/Routes
import React, { useContext } from "react";
import { Routes, Route } from "react-router-dom";
import { SignIn, SignUp, Dashboard } from "pages";
import AuthApi from "store/AuthApi";
export const ProtectedRouting = () => {
  return (
    <Routes >
      <Route path='/' exact element={<Dashboard />} />
      // add more protected routes
    </Routes>
  )
}
export const AuthRouting = () => {
  return (
    <Routes >
      <Route exact={true} path='/sign-in' element={<SignIn />} />
      <Route exact={true} path='/sign-up' element={<SignUp />} />
    </Routes>
  )
}
export const AllRoutes = ()=> {
  const context = useContext(AuthApi);
  console.log(context.user)
  return (
      context.user ?
  <ProtectedRouting />
 : <AuthRouting />
  )
}

頁面/SignIn.jsx

import React,{ useContext } from 'react';
import AuthApi from "store/AuthApi";

const SignIn = () => {
const context = useContext(AuthApi);
const signInSubmit =(e)=> {
   e.preventDefault();
   //post request to signin
   // if login is successfull then save user or token in cookie or localStorage or something
    context?.setUser(true);
  //...
}

  return (
    //signin code here
     <form onSubmit={signInSubmit}>
       ///input here
     </form>

  )
}

export default SignIn

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM