[英]Unable to get params when passing Parent's props to child component
我正在尝试构建一个简单的应用App Component
, IndexRoute
使用App Component
作为IndexRoute
列出博客
<Router history={browserHistory}> <Route path="/" component={Root}> <IndexRoute component={() => <App loader={this.props.fetching} posts={this.props.posts} fetching={this.props.fetching} fetched={this.props.fetched} />}> </IndexRoute> <Route path="form" component={Form}></Route> <Route path="about" component={About}></Route> <Route path="post/:id" component={SinglePost}></Route> </Route> </Router>
我试图在单击标题时使用SinglePost Component
显示single
博客文章。
import React from 'react'; class SinglePost extends React.Component { render(){ console.log("Single Post Props", this.props); return( <div> Passed: {this.props.params.id} </div> ); } } export default SinglePost;
所以,我得到了它的id
。 我可以访问它。 在App
组件中使用它:
<Route path="post/:id" component={SinglePost}></Route>
但是,我想传递父母的posts
道具
const mapStateToProps = (state) => {
return {
fetching: state.fetching,
fetched: state.fetched,
posts: state.posts,
error: state.error
}; };
我改变了路由器中的component = {}:
<Route path="post/:id" component={SinglePost}></Route>
进入这个(因为我搜索到这是在react-router [ react-router - 传递道具到处理程序组件 ]中传递道具的方式 :
<Route path="post/:id" component={() => <SinglePost posts={this.props.posts}/>} />
我怎样才能再次访问params
prop所以我可以通过传递的params
:id来对posts
数组进行排序?
您正在使用箭头功能。 箭头函数不会自动绑定此值,因此您需要手动绑定此值。
代码片段不起作用,它不会因为你只是简单地用纯HTML粘贴JSX代码。
但是,更换
<Route path="post/:id" component={() => <SinglePost posts={this.props.posts}/>} />
同
<Route path="post/:id" component={() => <SinglePost posts={this.props.posts.bind(this)}/>} />
应该工作,或者您可以使用function(){}为您绑定它。
编辑:
在react-router中传递props的首选方法
var props = {
prop1: "PropContent"
}
<SinglePost {...props} />
这可以在单个帖子组件中访问,
{this.props.route.prop1} // PropContent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.