簡體   English   中英

反應路由器dom v6子路由的問題

[英]problem with react router dom v6 subroutes

我正在做練習,我正在使用 react router dom v6 創建子路由,我遇到的問題是配置文件路由具有身份驗證,如果它經過身份驗證,它會向我顯示配置文件組件,否則它會將我發送到家,現在到這個 /profile 路由我創建了一個 /exerciselist 子路由,但是當我想訪問 /profile/exerciselist 時,該組件不會加載我,它直接將我發送到 /profile 路由,我怎樣才能讓它加載 profile/exerciselist 路由?

import React  from 'react'
import { BrowserRouter, Route, Routes, Navigate} from "react-router-dom"
import { useContext } from "react"
import { authContext } from "./context/authContext"
import Homepage from "./pages/Homepage"
import Login from "./pages/Login"
import Register from "./pages/Register"
import Notfound from "./pages/Notfound"
import Profile from "./pages/Profile"
import Footer from "./components/footer"
import ExercisesList from './components/exercises_list'
import "./public/css/appStyles/appStyles.css"

function App() {

  const { auth } = useContext(authContext)

  return (
    <BrowserRouter>

      <Routes>
        <Route path="/" element={!auth.auth ? <Homepage/> : <Navigate to="/profile" replace />}/>
        <Route path="/register" element={ !auth.auth ? <Register/> : <Navigate to="/profile" replace />}/>
        <Route path="/login" element={ !auth.auth ? <Login /> : <Navigate to="/profile" replace /> } />
        <Route path="/profile/*" element={ auth.auth ? <Profile />  : <Navigate to="/" replace /> } >
          <Route path="exerciselist" element={<ExercisesList/>} />
        </Route>
        <Route path="*" element={<Notfound/>}/>
      </Routes>

      <Footer/>
    </BrowserRouter>
  );
}

export default App;

渲染嵌套路由時,您有幾個選擇。

  1. 在父路由的組件中渲染一個Outlet組件,以便將嵌套的Route組件渲染到其中。

    例子:

     import { Outlet } from 'react-router-dom'; ... const Profile = () => {... return ( <>... Profile component JSX... <Outlet /> </> ); };

    刪除尾隨的"*" ,因為嵌套路由呈現到Outlet中。

     <Route path="/profile" element={ auth.auth? <Profile />: <Navigate to="/" replace />} > <Route path="exerciselist" element={<ExercisesList/>} /> </Route>
  2. 直接在路由組件中渲染一個Routes和嵌套的Route組件。

     import { Routes, Route } from 'react-router-dom'; ... const Profile = () => {... return ( <>... Profile component JSX... <Routes> <Route path="exerciselist" element={<ExercisesList/>} /> </Routes> </> ); };

    ...

     <Route path="/profile/*" // <-- trailing * allows matching nested routes element={ auth.auth? <Profile />: <Navigate to="/" replace />} />

暫無
暫無

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

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