如何在React Router V6中获取URL参数?

huangapple go评论116阅读模式
英文:

how to get a URL parameters in react router V6?

问题

"我有一个类似这样的URL:"

“http:something/forget/reset?type=text&c=$something&cc=$something”

"我想从这个路径获取参数,我使用了:"

  1. const params = useParams()

"但它返回一个空对象 {}。"

"我的当前路由如下:"

  1. <Route
  2. path="forget/reset"
  3. element={<ComponentA/>}
  4. />

"所以我应该像下面这样定义一个带参数的路由,还是有办法从URL中获取多个参数:"

  1. <Route path="forget" element={<ComponentA/>}>
  2. <Route
  3. path="forget/reset/:user/:c/:cc"
  4. element={<ComponentA/>}
  5. />
  6. </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:

  1. const params = useParams()

but it returns an empty object {}

my current route is like below:

  1. &lt;Route
  2. path=&quot;forget/reset&quot;
  3. element={&lt;ComponentA/&gt;}
  4. /&gt;

so should I define a route with parameters like below or is there a way to get multiple parameters form a url

  1. &lt;Route path=&quot;forget&quot; element={&lt;ComponentA/&gt;}&gt;
  2. &lt;Route
  3. path=&quot;forget/reset/:user/:c/:cc&quot;
  4. element={&lt;ComponentA/&gt;}
  5. /&gt;
  6. &lt;/Route&gt;

the above code also does not work.

答案1

得分: 1

  1. import { useSearchParams } from 'react-router-dom';
  2. const ComponentA = () => {
  3. const [searchParams] = useSearchParams();
  4. const type = searchParams.get("type"); // "text"
  5. const c = searchParams.get("c"); // "$something"
  6. const cc = searchParams.get("cc"); // "$something"
  7. // ...
  8. };
英文:

Given:

  • URL path &quot;/forget/reset?type=text&amp;c=$something&amp;cc=$something&quot;
  • Route &lt;Route path=&quot;forget/reset&quot; element={&lt;ComponentA /&gt;} /&gt;

For ComponentA to access the queryString params it should import and use the useSearchParams hook exported from react-router-dom@6.

  1. import { useSearchParams } from &#39;react-router-dom&#39;;
  2. const ComponentA = () =&gt; {
  3. const [searchParams] = useSearchParams();
  4. const type = searchParams.get(&quot;type&quot;); // &quot;text&quot;
  5. const c = searchParams.get(&quot;c&quot;); // &quot;$something&quot;
  6. const cc = searchParams.get(&quot;cc&quot;; // &quot;$something&quot;
  7. ...
  8. };

huangapple
  • 本文由 发表于 2023年1月9日 15:57:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054449.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定