在构造函数中声明React状态,在构造函数之外声明React状态 [英] Declaring React state, in constructor, versus out of constructor
问题描述
在构造函数之外声明 state
和有什么区别吗?
Is there any difference of declaring state
, out of constructor?
我在这里有一个组件示例:
I have an example of a component here:
class BurgerBuilder extends Component {
state = {
ingredients: {
salad: 0,
bacon: 0,
cheese: 0,
meat: 0
},
totalPrice: 30
};
....
}
在这里,我只声明一个名为state的变量,其中包括组件的变量,但我不调用构造函数.
Here I just declare a variable called state, which includes the variables of the component, but I don't call a constructor.
在我声明的地方:
class BurgerBuilder extends Component {
constructor() {
super();
this.state = {
ingredients: {
salad: 0,
bacon: 0,
cheese: 0,
meat: 0
},
totalPrice: 30
};
}
....
}
我发现,我可以将 this.setState
用于两种解决方案,并且我的项目没有真正的区别.是否有关于在何处使用的最佳实践.
I found, that I can use this.setState
for both solutions and that there is no real difference in my project. Is there a best practice, on what to use where.
推荐答案
有什么区别吗?是否有关于如何使用的最佳实践在哪里?
Is there any difference? Is there a best practice, on what to use where?
它们几乎相同.在没有 contructor()
的情况下声明 state
的语法为语法糖 .
They're almost the same. The syntax for declaring the state
without contructor()
is syntactic sugar.
在第一个示例中使用的称为类字段声明.(该提案于2017年7月进入第3阶段).
What you're using in the first example is called Class field declarations. (This proposal reached Stage 3 in July 2017).
简而言之,此建议使我们可以使用更简单的语法来声明类字段,而无需 constructor()
.
In short, this proposal allows us a simpler syntax for declaring class fields, without the need for the constructor()
.
例如,这些代码是使用ES2015编写的
For example, those codes are written using ES2015
class Counter extends HTMLElement {
constructor() {
super();
this.onclick = this.clicked.bind(this);
this.x = 0;
}
clicked() {
this.x++;
window.requestAnimationFrame(this.render.bind(this));
}
connectedCallback() { this.render(); }
render() {
this.textContent = this.x.toString();
}
}
window.customElements.define('num-counter', Counter);
通过使用类字段声明,他们会是这样的:
By using Class field declarations, they will be like this:
class Counter extends HTMLElement {
x = 0;
clicked() {
this.x++;
window.requestAnimationFrame(this.render.bind(this));
}
constructor() {
super();
this.onclick = this.clicked.bind(this);
}
connectedCallback() { this.render(); }
render() {
this.textContent = this.x.toString();
}
}
window.customElements.define('num-counter', Counter);
使用这种语法的好处:
通过预先声明字段,类定义变得更多自我证明;实例执行较少的状态转换,因为声明的字段始终存在.
By declaring fields up-front, class definitions become more self-documenting; instances go through fewer state transitions, as declared fields are always present.
这篇关于在构造函数中声明React状态,在构造函数之外声明React状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!