在构造函数中定义状态还是使用属性初始值设定项更好? [英] Is it better to define state in constructor or using property initializers?

查看:39
本文介绍了在构造函数中定义状态还是使用属性初始值设定项更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 this babel 文档,正确的在 React 中使用 ES6+ 的方法是这样初始化组件:

According to this babel documentation, the correct way to use ES6+ with React is to initial components like this:

class Video extends React.Component {
  static defaultProps = {
    autoPlay: false,
    maxLoops: 10,
  }
  static propTypes = {
    autoPlay: React.PropTypes.bool.isRequired,
    maxLoops: React.PropTypes.number.isRequired,
    posterFrameSrc: React.PropTypes.string.isRequired,
    videoSrc: React.PropTypes.string.isRequired,
  }
  state = {
    loopsRemaining: this.props.maxLoops,
  }
}

但是一些官方示例,例如 Dan Abramov 自己的 React DnD 模块,使用 ES6+ 但仍然在构造函数中定义状态:

But some official examples, like Dan Abramov's own React DnD module, uses ES6+ but still defines state within the constructor:

constructor(props) {
    super(props);
    this.moveCard = this.moveCard.bind(this);
    this.state = {
       // state stuff
    }
}

现在 Dan Abramov 作为 React 的重要贡献者,可能知道他可以在构造函数之外定义状态,但仍然选择在构造函数中进行.

Now Dan Abramov, being a significant contributor to React, probably knows that he can define state outside the constructor, yet still opts to do it within the constructor.

所以我只是想知道哪种方法更好,为什么?

So I'm just wondering which way is better and why?

推荐答案

我相信这是个人喜好的问题.转译后的输出在语义方面是相同的.

I believe it's a matter of personal preference. The transpiled output is the same in terms of semantics.

这篇关于在构造函数中定义状态还是使用属性初始值设定项更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆