我正在尝试将 react-router 与 props id 一起使用,但它给了我以下信息:
Matched leaf route at location "/some-12" does not have an element. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.
我正在使用 "react-router-dom": "6"和 "react": "^17.0.2"
//example Routes
import {Route, Routes } from "react-router-dom";
function App()
return(
<>
<Routes>
<Route path="/about" element={<About />}/>
<Route exec={true} path="/something" element={<Something/>}/>
<Route exact={true} path="/something-:id"
render={(props) => {
<Some id={props.match.params.id} />;}}
/>
<Route path="/contact" element={<Contact />}/>
</Routes>
</>```
//example Some
export default function Some({ id }) {
return(
<>
<p>Some with id: {id}
</>
)}
我哪里做错了?
最佳答案
在 react-router-dom
版本 6 中,Route
组件在 element
属性上呈现所有路由组件,并且不再有任何路由 props,即没有 history
、location
或 match
。
在 element
属性上渲染 Some
组件并使用 useParams
钩子(Hook)访问 id
路由匹配参数。如果 path="/something-:id"
不起作用,请尝试将 id
设为自己的路径段,即 path="/something/:id "
.
function App()
return(
<>
<Routes>
<Route path="/about" element={<About />}/>
<Route path="/something" element={<Something/>}/>
<Route path="/something-:id" element={<Some />} />
<Route path="/contact" element={<Contact />}/>
</Routes>
</>
);
}
...
import { useParams } from 'react-router-dom';
export default function Some() {
const { id } = useParams();
return(
<>
<p>Some with id: {id}
</>
);
}
关于javascript - 当我在路由中使用渲染时 react 返回 Outlet 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70438795/