javascript - 在 react-router-dom 中将 id 作为 props 传递

标签 javascript reactjs react-router-dom

我想将 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>

当我转到下一个 url img/2 时,路由器向我发送了正确的页面,但 id 不存在于 props 中。 当我查看 chrome 上的 React 开发人员工具时,我可以看到

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

在名为 component 的组件中,我在 props.match.params.imgId 中有一些东西 但是当我继续使用 Img 组件时,这是我所拥有的 Prop : imgId: {空对象}

你知道如何恢复参数中的id吗?

谢谢:)

最佳答案

你应该这样做:

第 1 步:更改您的路线声明

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

第二: 您应该像 this example 中那样从 react-router 注入(inject)的匹配中访问 Prop

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

当然,您可以轻松地将这些代码改编成您自己的代码。

关于javascript - 在 react-router-dom 中将 id 作为 props 传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51882003/

相关文章:

javascript - 记录与 socket.io 的连接和断开连接

javascript - 如何将 D3 圆与半圆对齐

reactjs - 如何将react-autosuggest内部的值传递给父组件?

javascript - 无法读取未定义的属性 - javascript 类

javascript - React router最新版本中,如何在首页嵌套路由 "/"

javascript - 如何将 $(this) 对象从一个函数传递到另一个函数?

javascript - 动态改变&lt;script&gt;标签src

javascript - ion-view 没有出现在 ion-nav-view 中

reactjs - React Router dom v5 中的嵌套路由和未找到路由

javascript - 当从 cookie 异步加载身份验证 token 时,React React-router-dom 私有(private)路由不起作用