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