簡體   English   中英

將Parent的props傳遞給子組件時無法獲取params

[英]Unable to get params when passing Parent's props to child component

我正在嘗試構建一個簡單的應用App ComponentIndexRoute使用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道具。 在此輸入圖像描述

我怎樣才能再次訪問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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM