我正在嘗試添加一個嵌套路由,它將連同它的父路由一起呈現到我的應用程式,但是當我添加嵌套路由時,整個檔案就會消失。為什么會這樣?我的代碼看起來有點像這樣:
import React from "react"
import {BrowserRouter, Routes, Route, Outlet} from "react-router-dom"
function Foo(){
return(
<div>
<h1>This is the parent</h1>
<Outlet />
</div>
)
}
function Child(){
return(
<div>
<p>This is the nested route</p>
</div>
)
}
function App(){
return(
<div>
<BrowserRouter>
<Routes>
<Route path='/parent' element={<Foo />}>
<Route path='/' element={<Child />}/>
</Route>
{/*Additional Routes and stuff*/}
</Routes>
</BrowserRouter>
</div>
)
}
當我運行它時,DOM 不會呈現。我得到所有路線的完全空白頁。當我洗掉該行時,<Route path='/' element={<Child />}/>一切都很好。這條線有什么問題會阻止其他所有內容呈現?
編輯:我解決了這個問題,但我不明白為什么這解決了這個問題。
因此,在該行中,<Route path='/' element={<Child />}/>我意外地從元素中洗掉了“/”字符path,使其成為<Route path='' element={<Child />}/>. 現在,DOM 渲染沒有任何問題。有人可以向我解釋一下,為什么這有效?我用于 React Router 的所有指南都在path元素中使用“/”字符。
uj5u.com熱心網友回復:
嵌套路由的路徑是相對于父路徑構建的,所以嵌套絕對路徑"/"下"/parent"是無效的。path=""實際上就像根本不指定路徑一樣,因此路由匹配并呈現。如果您希望子路由在與父組件相同的路徑上呈現,則使用prop指定它是索引路由。index
例子:
function App(){
return(
<div>
<BrowserRouter>
<Routes>
<Route path='/parent' element={<Foo />}>
<Route
index // <-- matches on `"/parent"`
element={<Child />}
/>
</Route>
{/*Additional Routes and stuff*/}
</Routes>
</BrowserRouter>
</div>
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/532774.html
上一篇:反應影像-本地影像未顯示
下一篇:更改下拉選單的外觀
