我遇到了一些反应代码,它们在类中定义了一个组件状态,如下所示:
// Snippet 1 class Sample extends React.Component { state = { count: 0 } }
// Snippet 2 class Sample extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } }
我能想到的唯一区别是初始化构造函数中的状态将保证状态在组件生命周期中正确初始化.
解决方法
您正在关注的是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….