将State初始化为类属性或在构造函数中[ReactJS] [英] Initialise State as a class property or in constructor [ReactJS]
问题描述
我已经看到两个案例设置了默认状态,例如:
I've seen tow cases set default state like:
class Page extends Component {
state = {
page: 0,
};
}
vs
class Page extends Component {
constructor(props) {
super(props);
this.state = { page: 0 };
}
}
使用第一种方法是否不好?我在哪里可以找到有关它的更多信息?还是该ecmascript的功能命名方式?
Use first variant Is it bad practice? Where can i find out more information about it? Or how this ecmascript's feature is named?
推荐答案
如果您具有 stage-,则可以使用第一个变体, 2个预置
,配置了babel。它是类属性语法,不包含在ES7提议中,但可作为babel的第二阶段预设使用。然而,使用第一或第二变体是优先事项。它们都转换为完全相同的东西。
You can use the first variant if you have stage-2 preset
configured with babel. It is a class property syntax and is not event included in ES7 proposal, however it is available as stage-2 preset with babel. However using the first or the second variant is a matter of preference. They both transpile to the exact same thing.
First method:
Second method
这篇关于将State初始化为类属性或在构造函数中[ReactJS]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!