根据这个 babel文档,使用ES6 +与React的正确方法是初始组件,如下所示:
class Video extends React.Component {
static defaultProps = {
autoPlay: false,
maxLoops: 10,
}
static propTypes = {
autoPlay: React.PropTypes.bool.isRequired,
maxLoops: React.PropTypes.number.isRequired,
posterFrameSrc: React.PropTypes.string.isRequired,
videoSrc: React.PropTypes.string.isRequired,
}
state = {
loopsRemaining: this.props.maxLoops,
}
}
Run Code Online (Sandbox Code Playgroud)
但是一些官方的例子,比如Dan Abramov自己的React DnD模块,使用ES6 +,但仍然在构造函数中定义状态:
constructor(props) {
super(props);
this.moveCard = this.moveCard.bind(this);
this.state = {
// state stuff
}
}
Run Code Online (Sandbox Code Playgroud)
现在,作为React的重要贡献者的Dan Abramov可能知道他可以在构造函数之外定义状态,但仍然选择在构造函数中执行它.
所以我只是想知道哪种方式更好,为什么?
import React, { Component } from 'react';
class Counter extends Component {
state = { value: 0 };
increment = () => {
this.setState(prevState => ({
value: prevState.value + 1
}));
};
decrement = () => {
this.setState(prevState => ({
value: prevState.value - 1
}));
};
render() {
return (
<div>
{this.state.value}
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
通常我看到的是人们在构造函数中执行this.state,如果他使用es6类.如果他不是,他可能使用getinitialstate函数放置状态.但是上面的代码(是的,它是一个工作代码),没有使用这两个.我有2个问题,这里的状态是什么?是一个局部变量?如果是,为什么它没有const
?prevState来自哪里?为什么在setState中使用箭头函数?这不是很容易this.setState({value:'something'})
吗?