2017-03-17 131 views
3

我有一個非常標準的設置,配頁陣營this.props未定義

import React from "react"; 
import ReactDOM from "react-dom"; 
import { IndexRoute, Router, Route, Link, hashHistory as history } from "react-router"; 

import Layout from "./pages/Layout"; 
... 
import User from "./pages/User"; 

ReactDOM.render(
    <Router history={history}> 
     <Route path="/" component={Layout}> 
     <IndexRoute component={...}/> 
     <Route path="project/create" component={...}/> 
     <Route path="project/:id" component={...}/> 
     <Route path="user/:id" component={User}/> 
     <Route path="*" component={...}/> 
     </Route> 
    </Router>, 
    document.getElementById("app-root")); 

一切工作完全不同的,當我去一個網頁一樣site.tld/#/user/5User成分有一定的麻煩實例化一個路由器正常。所有其他網頁正在工作,我也有另一個頁面使用網址參數(project/:id),它也工作得很好。

import React from "react"; 
... 

export default class User extends React.Component { 

    constructor() { 
    super(); 

    console.log(this); 

    ... 
    } 

    render() { 
    return ... 
    } 

這是我在控制檯中看到

enter image description here

我敢肯定它是最愚蠢的事情以後再,但我不能把它挑出來......

+0

通常,您將構造函數中收到的道具傳遞給組件超類:https://discuss.reactjs.org/t/should-we-include-the-props-parameter-to-class-constructors- when-declaring-components-using-es6-classes/2781 –

+0

嘗試在'render()'方法中記錄'this.props'來驗證。 –

+0

@HunterMcMillen你是對的,道具在渲染中可用,但不在構造函數中,在構造函數中傳遞道具使得我的代碼沒有區別:/ –

回答

9

我認爲你錯過了以下內容,替換你的構造函數

constructor(props) { 
    super(props); 

    console.log(this.props) 
} 

試一試,你應該從這裏得到輸出。props

React組件的構造函數在掛載之前被調用。 在實現React.Component子類的構造函數時, 應在任何其他語句之前調用super(props)。否則, this.props將在構造函數中未定義,這可能會導致 錯誤。

+1

我試過了,它不起作用。我在所有頁面中都有相同的構造函數,並且可以在其他頁面的構造函數中使用道具。 –

+0

@php_nub_qq你做超(道具)嗎?不只是super()而不是空的構造函數()而不是構造函數(道具) – Bruce

+0

是的,我在我發佈之前嘗試過。事實證明,在這個組件中,道具在render()中可用,但在構造函數中不可用。我想知道爲什麼.. –

相關問題