简体   繁体   English

初始化反应组件状态

[英]Initializing react component state

I came across some react code that defined a component state inside a class like follows: 我遇到了一些反应代码,它们在类中定义了一个组件状态,如下所示:

// Snippet 1
class Sample extends React.Component {
    state = {
        count: 0
    }
}

The way I've learnt React was to declare the state inside the constructor of a class: 我学习React的方法是在类的构造函数中声明状态:

// Snippet 2
class Sample extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0
        };
    }
}

The only difference I can think of is that initializing the state in the constructor would guarantee the state gets initialized properly in the component life cycle. 我能想到的唯一区别是初始化构造函数中的状态将保证状态在组件生命周期中正确初始化。

What are the differences between the above two code snippets? 上面两个代码片段之间有什么区别? In snippet 1, is it safe to assume that the state be properly set when the class is initialized? 在代码段1中,可以安全地假设在初始化类时正确设置状态?

What you're looking at is ES7+ Property Initializers . 您正在关注的是ES7+ Property Initializers It is done this way because Facebook knows Javascript will change in the future. 它是这样做的,因为Facebook知道Javascript将来会改变。 They want to be able to cope with those changes. 他们希望能够应对这些变化。

According to facebook ES7+ Property Initializers 根据facebook ES7 + Property Initializers

Wait, assigning to properties seems like a very imperative way of defining classes! 等等,分配属性似乎是定义类的一种非常必要的方式! You're right, however, we designed it this way because it's idiomatic. 你是对的,但是,我们这样设计它是因为它是惯用的。 We fully expect a more declarative syntax for property initialization to arrive in future version of JavaScript.... 我们完全期望在将来的JavaScript版本中使用更具声明性的属性初始化语法....

Here is the Facebook link Also more info here 这里是Facebook 链接还有更多信息在这里

also a Link to the proposal 也是该提案链接

在babel上使Class看起来更干净只是一种语法糖: https//babeljs.io/docs/plugins/transform-class-properties/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM