简体   繁体   English

嵌套路由中的 React Router V6 useParams 不工作

[英]React Router V6 useParams inside nested routes NOT Working

I have created a custom page with path "/:name" inside a nested route.我在嵌套路由中创建了一个路径"/:name"的自定义页面。 I expected the output to be Hello, my friend {name} , instead I am getting an error saying ERR_ABORTED 404 (Not Found) .我希望 output 是Hello, my friend {name} ,但我收到一条错误ERR_ABORTED 404 (Not Found) How do I fix this?我该如何解决?

Route Page路线页面

import React from 'react'
import { Routes, Route } from 'react-router-dom'
import HomePage from './Pages/HomePage'
import OtherPage from "./Pages/OtherPage"
import ErrorPage from './Pages/ErrorPage'
import MainProduct from "./Pages/projects/MainProduct"
import FirstProduct from "./Pages/projects/otherProduct/FirstProduct"
import SecondProduct from "./Pages/projects/otherProduct/SecondProduct"
import CustomProduct from "./Pages/projects/otherProduct/CustomProduct"
import MainNavComponent from './Components/MainNavComponent'

export default function App() {
    return (
        <div>
            <MainNavComponent />
            <Routes>
                <Route path='/' element={<HomePage />} />
                <Route path='/mainProduct' element={<MainProduct />}>
                    <Route path='firstProduct' element={<FirstProduct />} />
                    <Route path='secondProduct' element={<SecondProduct />} />
                    <Route exact path=":name" element={<CustomProduct />} />
                </Route>
                <Route path='/otherPage' element={<OtherPage />} />
                <Route path='*' element={<ErrorPage />} />
                <Route exact path=":name" element={<CustomProduct />} />

            </Routes>
        </div>
    )
}

Custom Route Page自定义路由页面

export default function CustomProduct() {

    let { name } = useParams()

    return (
        <div>
            <h1>Hello, my friend {name}</h1>
        </div>
    )
}
 add  <BrowserRouter> before <Routes> tag and close it( </BrowserRouter>) after </Routes>

try this for your routes /mainProduct/{yourname} because your:name inside /mainProduct Route为你的路线尝试这个/mainProduct/{yourname}因为 your:name inside /mainProduct Route

 <Route path='/mainProduct' element={<MainProduct />}>
    <Route path='firstProduct' element={<FirstProduct />} />
    <Route path='secondProduct' element={<SecondProduct />} />
    <Route exact path=":name" element={<CustomProduct />} />
 </Route>

try this link /mainProduct/{yourname} such as: /mainProduct/name1 or /mainProduct/name2尝试此链接/mainProduct/{yourname}例如: /mainProduct/name1/mainProduct/name2

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

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