2016-09-27 48 views
0

根據標題,爲什麼最初this.props失敗?更實際的是,如果你依賴構造函數中的道具,你如何解決這個問題?例如,我想在我的訂閱中引用道具?爲什麼我無法在反應構造函數中訪問默認道具,但我可以渲染?

class AboutBox extends Component { 
    static defaultProps = { 
    title: 'Undefined Product', 
    } 
    constructor() { 
    super(); 
    console.log(this.props.title); //this fails (=> null) 
    } 
    render() { 
    console.log(this.props.title); //this works (=> 'Undefined Product') 
    return null; 
    } 
} 
+1

相關:http://stackoverflow.com/q/30571875/2088135 –

+0

可能重複[使用es6類時React中「super()」和「super(props)」之間的區別是什麼?](http: //www.stackoverflow.com/questions/30571875/whats-the-difference-between-super-and-superprops-in-react-when-using-e) –

回答

4

你必須把在構造ARGS道具,並傳遞給內部構造超

constructor(props){ 
    super(props); 
    console.log(props.title); 
} 

使用的道具,這個工作還可以,但有一些問題transpilation針對IE

+0

謝謝Daniele! – ElJefeJames

1

嘗試添加道具到constructor()參數,並在super()電話:

constructor(props) { 
    super(props); 
    console.log(props.title); 
} 
+1

謝謝Piotr!這也是正確的 – ElJefeJames

0

如果要在構造函數中使用this.props,則需要將props傳遞給super()。否則,這並不重要,因爲在調用構造函數之後,React立即在外部實例上設置.props

相關問題