[英]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.