我遇到了一些在类中定义组件状态的 React 代码,如下所示:
// 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....
关于javascript - 初始化 react 组件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41133240/