简体   繁体   English

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

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

Protected Routes.js:受保护的 Routes.js:

In protected routes you can see I'm using directly false in if statement but I'm still able to see that page why?在受保护的路由中,您可以看到我在 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: This is app.js where I'm using protected routes component 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;

First, <Routes> elements should only have <Route> elements as children.首先, <Routes>元素应该只有<Route>元素作为子元素。 You should move your protection logic down a layer.您应该将保护逻辑向下移动一层。

Secondly, the render prop doesn't exist anymore in V6.其次, render道具在 V6 中不再存在。 It was replaced in favor of element .它被替换为element See doc .请参阅文档

Here is how you might tackle it:以下是您可以解决的方法:

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

And:和:

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

  return children;
};

you can use createContext & useContext您可以使用 createContext 和 useContext

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

Then define the context app.jsx然后定义上下文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

then see AllRoutes然后查看 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 />
  )
}

pages/SignIn.jsx页面/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