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

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

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:

  &lt;Route
    path=&quot;forget/reset&quot;
    element={&lt;ComponentA/&gt;}
  /&gt;

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

&lt;Route path=&quot;forget&quot; element={&lt;ComponentA/&gt;}&gt;
  &lt;Route
    path=&quot;forget/reset/:user/:c/:cc&quot;
    element={&lt;ComponentA/&gt;}
  /&gt;
&lt;/Route&gt;

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 &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.

import { useSearchParams } from &#39;react-router-dom&#39;;

const ComponentA = () =&gt; {
  const [searchParams] = useSearchParams();

  const type = searchParams.get(&quot;type&quot;); // &quot;text&quot;
  const c = searchParams.get(&quot;c&quot;);       // &quot;$something&quot;
  const cc = searchParams.get(&quot;cc&quot;;      // &quot;$something&quot;

  ...

};

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:

确定