react state定义的3种方式

react中state定义的3种方式

大家都知道的在react组件中,我们通过props和state来控制数据,props是在父组件中被指定的
而且一经指定,在被指定的组件的生命周期内是不能够进行改变的,对于需要改变的数据,只能依托
state来进行处理了,所以就引申出了一个话题,如何初始化state呢?
我根据react的发展历程来进行总结出3中写法。

ES5 在getInitialState中进行设置

1
2
3
4
5
6
7
8
9
10
var MyComponent = React.createClass({
getInitialState:function(){
disable:false
}
render:function(){
return (
<button disable={this.state.disable}>submit<\/button>
)
}
})

这种写法是es5的写法,比较老了,不推荐使用这种方式写,当时出现这种方式主要是因为webpack和 babel还未兴起,现在他们大行其道,自然大家更倾向于es6的写法了。

ES6 在constructor中进行设置

1
2
3
4
5
6
7
8
9
10
11
12
13
class MyComponent extends PureComponent {
constructor(props){
super(props)
this.state = {
disable:false
}
}
render(){
return (
<button disable={this.state.disable}>submit<\/button>
)
}
}

es6提出了class的概念,constructor作为一个类的入口,每次初始化的时候都会执行constructor中的代码,所以我们可以将state写在构造函数中,这个也是react官方推荐的写法。

ES7 定义实例属性

1
2
3
4
5
6
7
8
9
10
class MyComponent extends PureComponent {
state = {
disable:false
}
render(){
return (
<button disable={this.state.disable}><\/button>
)
}
}

ES6中不支持在class中定义类的属性,只能定义方法,例如:

1
2
3
4
5
6
7
class Foo{
name:a,
method(){
console.log(this.name)
}
}
Foo.name //undefined

而在ES7的提案中允许通过“=”赋值的方法设置类的实例属性。

<完>