英文:
how to get a URL parameters in react router V6?
问题
"我有一个类似这样的URL:"
“http:something/forget/reset?type=text&c=$something&cc=$something”
"我想从这个路径获取参数,我使用了:"
const params = useParams()
"但它返回一个空对象 {}。"
"我的当前路由如下:"
<Route
path="forget/reset"
element={<ComponentA/>}
/>
"所以我应该像下面这样定义一个带参数的路由,还是有办法从URL中获取多个参数:"
<Route path="forget" element={<ComponentA/>}>
<Route
path="forget/reset/:user/:c/:cc"
element={<ComponentA/>}
/>
</Route>
"上述代码也不起作用。"
英文:
I have a URL like this :
"http:something/forget/reset?type=text&c=$something&cc=$something"
I want to get the parameters form this path and I used:
const params = useParams()
but it returns an empty object {}
my current route is like below:
<Route
path="forget/reset"
element={<ComponentA/>}
/>
so should I define a route with parameters like below or is there a way to get multiple parameters form a url
<Route path="forget" element={<ComponentA/>}>
<Route
path="forget/reset/:user/:c/:cc"
element={<ComponentA/>}
/>
</Route>
the above code also does not work.
答案1
得分: 1
import { useSearchParams } from 'react-router-dom';
const ComponentA = () => {
const [searchParams] = useSearchParams();
const type = searchParams.get("type"); // "text"
const c = searchParams.get("c"); // "$something"
const cc = searchParams.get("cc"); // "$something"
// ...
};
英文:
Given:
- URL path
"/forget/reset?type=text&c=$something&cc=$something"
- Route
<Route path="forget/reset" element={<ComponentA />} />
For ComponentA
to access the queryString params it should import and use the useSearchParams
hook exported from react-router-dom@6
.
import { useSearchParams } from 'react-router-dom';
const ComponentA = () => {
const [searchParams] = useSearchParams();
const type = searchParams.get("type"); // "text"
const c = searchParams.get("c"); // "$something"
const cc = searchParams.get("cc"; // "$something"
...
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论