admin管理员组文章数量:1340287
I'm trying to add an optional query parameter to the end of a path, so the URL would look like this: "/user/1/cars?makeYear=2020"
or "/user/1/cars"
. The relevant Route
is defined as follows. I'm unable to find guidance on how to add an optional query parameter to an existing path. For example, the following doesn't work:
<Route path="user" element={<UserScreen />}>
<Route path=":id/makeYear?" element={<User/>} />
</Route>
Here I'd think that <Route path=":id/makeYear?" element={<User/>} />
will mark makeYear
as an optional parameter, but no, doesn't work.
I then thought that I'd access the query parameters directly in the ponent, so given that the URL is "/user/1/cars?makeYear=2020"
, I can fetch the URL via the useLocation
api provided by react-router-dom
. However, the query parameter, this doesn't work either as the query parameter is immediately removed from the URL (I'm guessing by react-router
).
I'm using react-router-dom
(6.2.2).
I'm trying to add an optional query parameter to the end of a path, so the URL would look like this: "/user/1/cars?makeYear=2020"
or "/user/1/cars"
. The relevant Route
is defined as follows. I'm unable to find guidance on how to add an optional query parameter to an existing path. For example, the following doesn't work:
<Route path="user" element={<UserScreen />}>
<Route path=":id/makeYear?" element={<User/>} />
</Route>
Here I'd think that <Route path=":id/makeYear?" element={<User/>} />
will mark makeYear
as an optional parameter, but no, doesn't work.
I then thought that I'd access the query parameters directly in the ponent, so given that the URL is "/user/1/cars?makeYear=2020"
, I can fetch the URL via the useLocation
api provided by react-router-dom
. However, the query parameter, this doesn't work either as the query parameter is immediately removed from the URL (I'm guessing by react-router
).
I'm using react-router-dom
(6.2.2).
1 Answer
Reset to default 11react-router-dom
doesn't use the queryString for route path matching. Remove the queryString part from the route path
prop. Access the query params in the ponent via the useSearchParams hook.
<Route path=":id" element={<User/>} />
...
import { useSearchParams } from 'react-router-dom';
const User = () => {
const [searchParams] = useSearchParams();
const makeYear = searchParams.get("makeYear");
// handle logic based on makeYear
...
};
本文标签: javascriptAdd optional query parameters to a dynamic path using React RouterStack Overflow
版权声明:本文标题:javascript - Add optional query parameters to a dynamic path using React Router - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743610700a2509966.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论