简体   繁体   English

在 react-router-dom 中将 id 作为道具传递

[英]Pass id as props in react-router-dom

I would like to pass an ID in props to a component react I use react-router-dom Here is my app.js file我想将 props 中的 ID 传递给组件 react 我使用 react-router-dom 这是我的 app.js 文件

          <Switch location={this.props.location}>
        <Route exact path="/" component={Home} />
        <Route path="/list" component={List} />
        <Route path='/img/:imgId' component={() => <Img imgId={this.props.params.imgId}/>} />
      </Switch>

When I go to the next url img / 2, the router sends me the right page, but the id is not present in the props.当我转到下一个 url img / 2 时,路由器向我发送了正确的页面,但道具中不存在 id。 When I look into react developer tools on chrome, I can see that当我在 chrome 上查看 React 开发人员工具时,我可以看到

<Switch>
 <Route>
  <component>
   <Img>
   </Img>
  </component>
 </Route>
</Switch>

In the component called component, I have something in props.match.params.imgId But when I go on the Img component, here is what I have as props: imgId: {empty object}在名为 component 的组件中,我在 props.match.params.imgId 中有一些东西但是当我继续使用 Img 组件时,这里是我拥有的道具: imgId: {empty object}

Do you know how to recover the id in parameter?你知道如何恢复参数中的id吗?

Thanks :)谢谢 :)

You should do it like this:你应该这样做:

1st: change your Route declaration第一:改变你的路线声明

<Switch location={this.props.location}>
  <Route exact path="/" component={Home} />
  <Route path="/list" component={List} />
  <Route path='/img/:imgId' component={Img} />
</Switch>

2nd: you should access the prop from match injected by react-router like in this example第二:你应该像在 这个例子中一样从 react-router 注入的 match 访问 prop

const Img = ({ match }) => (
  <div>
    <h3>IMAGE ID: {match.params.imgId}</h3>
  </div>
);

but of course you can easily adapt that code into your own.但当然,您可以轻松地将该代码改编为您自己的代码。

You would use the functional callback pattern in case where you want to pass some props other than router props to the component.如果您想将除路由器道具以外的一些道具传递给组件,您将使用函数式回调模式。 In your case you can simply render the Img component在您的情况下,您可以简单地呈现Img组件

<Switch location={this.props.location}>
   <Route exact path="/" component={Home} />
   <Route path="/list" component={List} />
   <Route path='/img/:imgId' component={Img} />
</Switch>

and access the imgId in Img component like this.props.match.params.id .和访问imgIdImg像分量this.props.match.params.id

However to point out the problem in your current code, it doesn't work correctly because you are trying to pass the parents match props to the Img component whereas you need to pass the Route's own props like但是,要指出当前代码中的问题,它无法正常工作,因为您试图将父匹配道具传递给Img组件,而您需要传递 Route 自己的道具,例如

<Switch location={this.props.location}>
    <Route exact path="/" component={Home} />
    <Route path="/list" component={List} />
    <Route path='/img/:imgId' component={(routerProps) => <Img imgId={routerProps.match.params.imgId}/>} />
</Switch>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM