2017-07-25 87 views
1

我爲學校的記錄系統構建了一個項目,在該項目中我使用React構建了前端。在管理頁面的主要組成部分,我想有一個可以在管理對話框中導航的反應路由器。正如我試圖實現這一點,發生以下問題:當嘗試通過反應路由組件傳遞參數給一個類時,子組件不會收到任何道具。反應組件接收道具爲undefined

我有以下的反應組件層次:

class Test extends React.Component { 
    constructor() { 
     super(); 

     console.log("in class: " + this.props) 
    } 

    render() { return <div>test</div>} 
} 

class AdminPage extends BasicPage { 
    /* Other class functions here... */ 
    render() { 
     let pageBody = ""; 
     if(!this.state.isLoading) 
      pageBody = (
       <Router> 
        <Switch> 
         <Route path={"/:schoolName/admin"} component={AdminMenu} exact/> 
         <Route path={"/:schoolName/admin/view/:id"} exact 
          component={() => <Test par1="abc" />} /> 
        </Switch> 
       </Router> 
      ); 
     return (
      <Layout title={ this.state.isLoading ? 
       TITLE_UNTIL_LOADED : 
       PAGE_TITLE + this.state.schoolPrefs.heb_name} 
        subtitle={ this.state.subtitle } 
        notification={ this.state.notification } 
        isLoading={ this.state.isLoading } 
      > 
       {pageBody} 
      </Layout> 
     ); 
    } 
} 

當我去/Random Name/admin/view/someID,它打印到控制檯in class: undefined

然後我想看看問題出在傳遞組件還是接收組件。我定義的函數otherTest(props)如下:

function otherTest(props) { 
    console.log("Function props: " + props); 
    return (<Test {...props} />); 
} 

然後改變了路線組成,像這樣:

<Route path={"/:schoolName/admin/view/:id"} exact 
    component={otherTest} /> 

然後當我去/Random Name/admin/view/someID,我看到的功能收到的道具就好了,但在<Test … />內的日誌仍然打印undefined

我還試圖在主要呈現功能的{pageBody}變量之後加入<Test param1=」123」 />,但它印刷in class: undefined爲好。

有人知道問題出在哪裏嗎?

謝謝。

回答

2

你必須從構造函數中取道具參數,然後傳遞給super。

constructor(props){ 
super(props); 
} 
0

不要只在創建類時刻構造函數中使用this.props怎麼一回事,因爲構造火災。使用此代碼:

constructor(props) { 
super(props); 

console.log(props); 
}