2017-07-25 71 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); 
} 
相关问题