2016-09-27 47 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

相关问题