反应中的路线参数

时间:2020-04-15 13:10:07

标签: reactjs

我有很多路线

<Route exact path="/"  component={Test} />
<Route exact path="/1"  component={Test1} />
<Route exact path="/2"  component={Test2} />

在每个组件中,我都使用useLocation从路由中获取数据。是否有可能在每个组件中传递Route参数并使用useLocation访问该参数?

以下是示例:

<Route exact path="/" parameter='this is route nr 1'  component={Test} />
<Route exact path="2/" parameter='this is route nr 2'  component={Test2} />

哪种方法可以解决我想要达到的目标?

3 个答案:

答案 0 :(得分:1)

对于查询参数,您无需在<Route />中做任何额外的事情。您只需要在组件中获取这些查询参数并对其进行解析

要从url访问param1

/?param1=hello

import { useLocation } from 'react-router-dom';
const Test = () => {
  const queryParams = new URLSearchParams(useLocation().search);
  return (
    <div>Test {queryParams.get('param1')}</div>
  );
}

如果您想要像这样的路径参数

/1 //从这条路线出发1

在路线中,您无需创建多个路线就可以获取1,2等

<Route exact path="/:id" component={Test} />

在组件中

import { useParams } from 'react-router-dom';
const Test = () => {
  let { id } = useParams();
  return (
    <div>Test ID: {id}</div>
  );
}

答案 1 :(得分:1)

从您的问题看来,您似乎在寻找一种仅在路由器声明处将数据传递到路由的方法。因此,您可以使用常规道具代替位置数据提取-


 <Route exact path="/" render={()=><Test parameter={'this is route nr 1'} />} />

答案 2 :(得分:1)

您可以使用渲染直接将props传递给组件:

<Route
  exact
  path="/"
  render={props => <MyComponent {...props} foo="hello world" bar={false} /> }
/>

或者您可以使用查询参数:

<Route
  exact
  path={`/user?id=${user_id}`}
  component={MyComponent}
/>

,然后在MyComponent中可以访问props.match.params.id

React-router文档是一个很好的开始