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

Coh*_*chi 6 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>
Run Code Online (Sandbox Code Playgroud)

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

<Switch>
 <Route>
  <component>
   <Img>
   </Img>
  </component>
 </Route>
</Switch>
Run Code Online (Sandbox Code Playgroud)

在名为 component 的组件中,我在 props.match.params.imgId 中有一些东西但是当我继续使用 Img 组件时,这里是我拥有的道具: imgId: {empty object}

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

谢谢 :)

Joã*_*nha 7

你应该这样做:

第一:改变你的路线声明

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

第二:你应该像在这个例子中一样从 react-router 注入的 match 访问 prop

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

但当然,您可以轻松地将该代码改编为您自己的代码。