[英]Unable to get params when passing Parent's props to child component
I am trying to build a simple app which just lists blogs using App Component
as IndexRoute
我正在尝试构建一个简单的应用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>
I am trying to display, the single
blog post using SinglePost Component
when the title is clicked. 我试图在单击标题时使用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;
So, I am getting its id
. 所以,我得到了它的id
。 and I can access it. 我可以访问它。 Using this in App
Component: 在App
组件中使用它:
<Route path="post/:id" component={SinglePost}></Route>
But, i want to pass the posts
props in the parent 但是,我想传递父母的posts
道具
const mapStateToProps = (state) => {
return {
fetching: state.fetching,
fetched: state.fetched,
posts: state.posts,
error: state.error
}; };
SO i changed the component={} in the Router from: 我改变了路由器中的component = {}:
<Route path="post/:id" component={SinglePost}></Route>
into this(as I searched that this is the way to pass props in react-router [ react-router - pass props to handler component ): 进入这个(因为我搜索到这是在react-router [ react-router - 传递道具到处理程序组件 ]中传递道具的方式 :
<Route path="post/:id" component={() => <SinglePost posts={this.props.posts}/>} />
Now, i am getting this error because it is not getting the params
prop. 现在,我收到这个错误,因为它没有获得params
道具。
How can I access the params
prop again so I can sort the array of posts
by via passed params
:id ? 我怎样才能再次访问params
prop所以我可以通过传递的params
:id来对posts
数组进行排序?
You are using Arrow Functions. 您正在使用箭头功能。 Arrow Functions do not bind this value automatically, So you need to do bind this manually. 箭头函数不会自动绑定此值,因此您需要手动绑定此值。
The code Snippet doesn't works, And it won't because you simply pasted JSX code in plain HTML. 代码片段不起作用,它不会因为你只是简单地用纯HTML粘贴JSX代码。
But, Replacing 但是,更换
<Route path="post/:id" component={() => <SinglePost posts={this.props.posts}/>} />
with 同
<Route path="post/:id" component={() => <SinglePost posts={this.props.posts.bind(this)}/>} />
should work, or you can use function() {} to bind this for you. 应该工作,或者您可以使用function(){}为您绑定它。
Edit: 编辑:
Preferred way of passing props in react-router 在react-router中传递props的首选方法
var props = {
prop1: "PropContent"
}
<SinglePost {...props} />
And this can be accessed in Single post component, 这可以在单个帖子组件中访问,
{this.props.route.prop1} // PropContent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.