[英]useParams() unable to fetch path dynamically react-router v6
import { Route, Routes, Navigate } from "react-router-dom";
import AllQuotes from './pages/AllQuotes';
import QuoteDetail from './pages/QuoteDetail';
function App() {
return (
<div>
<Routes>
<Route path='/' element={<Navigate to='/quotes' />} />
<Route path='/quotes' element={<AllQuotes />} />
<Route path='/quotes/*' element={<QuoteDetail />} />
<Route path='/quotes/:quoteId' element={<QuoteDetail />} />
</Routes>
</div>
);
}
export default App;
this is my Quote details code这是我的报价详情代码
import { Fragment } from "react";
import { useParams } from "react-router";
import { Routes, Route } from "react-router-dom";
import Comments from "../components/comments/Comments";
const QuoteDetail = () => {
const params = useParams();
console.log(params.quoteId);
return (
<Fragment>
<h1>Quote Detail Page</h1>
<p>{params.quoteId}</p>
<Routes>
<Route
path={`${params.quoteId}/comments`}
element={<p>Hello</p>}
/>
</Routes>
</Fragment>
);
};
export default QuoteDetail;
My code is unable to render the elements of the nested route component present in my QuoteDetail code block while I'm using the dynamic path value当我使用动态路径值时,我的代码无法呈现 QuoteDetail 代码块中存在的嵌套路由组件的元素
If QuoteDetail
is rendering sub-routes then specify the *
wildcard at the end of of the "quoteId" route to allow further/more deeply matching.如果
QuoteDetail
正在呈现子路由,则在“quoteId”路由的末尾指定*
通配符以允许进一步/更深入的匹配。
function App() {
return (
<div>
<Routes>
<Route path='/' element={<Navigate to='/quotes' />} />
<Route path='/quotes' element={<AllQuotes />} />
<Route path='/quotes/:quoteId/*' element={<QuoteDetail />} />
</Routes>
</div>
);
}
You can also use relative matching/linking from the QuoteDetail
, it's actually not necessary to know the current quoteId
to create links to, and match, further sub-routes.您还可以使用
QuoteDetail
中的相对匹配/链接,实际上不需要知道当前的quoteId
来创建链接并匹配进一步的子路由。 You can just specify the relative path from the current location.您可以只指定当前位置的相对路径。 Paths starting with
"/"
are absolute, and without are relative.以
"/"
开头的路径是绝对的,没有的是相对的。
const QuoteDetail = () => {
const params = useParams();
return (
<Fragment>
<h1>Quote Detail Page</h1>
<p>{params.quoteId}</p>
<Routes>
<Route
path="comments"
element={<p>Hello</p>}
/>
</Routes>
</Fragment>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.