Issue
为什么这不起作用?
const App = () =>
<Routes>
<Route path='/abc' element={<p>abc</p>} />
<Route element={<MyComponent />}></Route>
</Routes>
const MyComponent = () =>
<Routes>
<Route path='/def' element={<p>def</p>} />
</Routes>
我认为你把布局路径与100条路径的作用与101条路径混为一谈,任何路由组件都可以在ReactTree中进一步渲染.像这样的无路径布局路由不参与路由匹配,因此它希望声明嵌套路由以便they可以参与.
const App = () =>
<Routes>
<Route path='/abc' element={<p>abc</p>} />
<Route element={<MyComponent />}>
{/* no nested routes to match 🤷🏻♂️ */}
</Route>
</Routes>
Explanation
布局路由
使用布局布线时,可以直接包裹和渲染嵌套布线.布局路由的目的是提供一些"公共UI"和一个Outlet
,用于嵌套路由将其内容呈现到其中.
使用布局路由的示例.
const App = () => (
<Routes>
<Route path='/abc' element={<p>abc</p>} />
<Route element={<MyComponent />}> // <-- parent route
<Route // <-- nested route
path='def' // <-- "/def"
element={<p>def</p>} // <-- rendered into Outlet
/>
</Route>
</Routes>
);
const MyComponent = () => (
<div>
{/* Common UI header, etc */}
<Outlet />
{/* Common UI footer, etc */}
</div>
);
后代路由
在呈现后代路由时,布局路由不起作用.
One 102 distinction though is that in order for descendent routes to be reachable and matchable the parent route 103 append the wildcard matcher, or 100, to its 101.
后代路由建立其到其父路由的路径relative.这就是为什么当您向父路由添加path="*"
时,您的代码工作.这将与第一条路由匹配的"/abc"
相匹配.
使用派生路由的示例.
const App = () => (
<Routes>
<Route path='/abc' element={<p>abc</p>} />
<Route // <-- parent route
path="*" // <-- match anything but "/abc"
element={<MyComponent />}
/>
</Routes>
);
const MyComponent = () => (
<div>
{/* Common UI header, etc */}
<Routes>
<Route // <-- descendent route
path='def' // <-- "/" + "def" -> "/def"
element={<p>def</p>}
/>
</Routes>
{/* Common UI footer, etc */}
</div>
);