javascript – 初始化反应组件状态

前端之家收集整理的这篇文章主要介绍了javascript – 初始化反应组件状态前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我遇到了一些反应代码,它们在类中定义了一个组件状态,如下所示:
// Snippet 1
class Sample extends React.Component {
    state = {
        count: 0
    }
}

我学习React的方法是在类的构造函数中声明状态:

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

我能想到的唯一区别是初始化构造函数中的状态将保证状态在组件生命周期中正确初始化.

上面两个代码片段之间有什么区别?在代码段1中,假设在初始化类时正确设置状态是否安全?

解决方法

您正在关注的是ES7 Property Initializers.它是这样做的,因为Facebook知道Javascript将来会改变.他们希望能够应对这些变化.

According to 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….

这是Facebook link
还有更多信息here

也是Link to the proposal

猜你在找的JavaScript相关文章