【发布时间】:2016-08-02 05:40:45
【问题描述】:
我总是编写 React 代码,尤其是在 ES6 类中。但我的问题是,我们什么时候在 React Components 中使用constructor(props)? constructor(props) 行是否与组件及其道具的渲染有关?
【问题讨论】:
标签: javascript reactjs ecmascript-6
我总是编写 React 代码,尤其是在 ES6 类中。但我的问题是,我们什么时候在 React Components 中使用constructor(props)? constructor(props) 行是否与组件及其道具的渲染有关?
【问题讨论】:
标签: javascript reactjs ecmascript-6
接受的答案不正确(可能只是误用了“render”这个词)。
正如我在评论中解释的那样,React 组件的构造函数在组件第一次安装或实例化时执行。在随后的渲染中永远不会再次调用它。
通常构造函数用于设置组件的内部state,例如:
constructor () {
super()
this.state = {
// internal state
}
}
或者,如果你有可用的类属性语法(例如via Babel),如果你只是为了初始化状态,你可以放弃声明构造函数:
class Example extends React.Component {
state = {
// internal state
}
}
constructor(props) 行是否与组件及其 props 的渲染有关?
构造函数并不直接规定组件渲染的内容。
组件渲染的内容由其render 方法的返回值定义。
【讨论】: