函数定义组件
function Clock(props) {return (<div><h1>Hello, world!</h1><h2>It is {props.date.toLocaleTimeString()}.</h2></div>);}function tick() {ReactDOM.render(<Clock date={new Date()} />,document.getElementById('root'));}setInterval(tick, 1000
然而,它错过了一个关键的要求:Clock设置一个定时器并且每秒更新UI应该是Clock的实现细节。
理想情况下,我们写一次 Clock 然后它能更新自身:
ReactDOM.render(<Clock />,document.getElementById('root'));
为了实现这个需求,我们需要为Clock组件添加”状态(state)”
状态与属性十分相似,但是状态是私有的,完全受控于当前组件。
我们之前提到过,定义为类的组件有一些额外的特性。局部状态就是如此:只能用于类的一个功能。
将函数转换为类(特有局部状态)
你可以通过5个步骤将函数组件 Clock 转换为类
- 创建一个名称扩展为
React.Component的ES6 类 - 创建一个叫做
render()的空方法 - 将函数体移动到
render()方法中 - 在
render()方法中,使用this.props替换props - 删除剩余的空函数声明
class Clock extends React.Component {render() {return (<div><h1>Hello, world!</h1><h2>It is {this.props.date.toLocaleTimeString()}.</h2></div>);}}
Clock 现在被定义为一个类而不只是一个函数
使用类就允许我们使用其它特性,例如局部状态、生命周期钩子
为一个类添加局部状态
我们会通过3个步骤将 date 从属性移动到状态中:
在
render()方法中使用this.state.date替代this.props.dateclass Clock extends React.Component {render() {return (<div><h1>Hello, world!</h1><h2>It is {this.state.date.toLocaleTimeString()}.</h2></div>);}}
添加一个类构造函数来初始化状态
this.stateclass Clock extends React.Component {constructor(props) {super(props);this.state = {date: new Date()};}render() {return (<div><h1>Hello, world!</h1><h2>It is {this.state.date.toLocaleTimeString()}.</h2></div>);}}
注意我们如何传递
props到基础构造函数的:constructor(props) {super(props);this.state = {date: new Date()};}
类组件应始终使用
props调用基础构造函数。从
<Clock />元素移除date属性:ReactDOM.render(<Clock />,document.getElementById('root'));
稍后将定时器代码添加回组件本身。
结果如下:class Clock extends React.Component {constructor(props) {super(props);this.state = {date: new Date()};}render() {return (<div><h1>Hello, world!</h1><h2>It is {this.state.date.toLocaleTimeString()}.</h2></div>);}}ReactDOM.render(<Clock />,document.getElementById('root'));
将生命周期方法添加到类中
在具有许多组件的应用程序中,在销毁时释放组件所占用的资源非常重要。
每当Clock组件第一次加载到DOM中的时候,我们都想生成定时器,这在React中被称为挂载
同样,每当Clock生成的这个DOM被移除的时候,我们也会想要清除定时器,这在React中被称为卸载。
我们可以在组件类上声明特殊的方法,当组件挂载或卸载时,来运行一些代码:class Clock extends React.Component {constructor(props) {super(props);this.state = {date: new Date()};}componentDidMount() {}componentWillUnmount() {}render() {return (<div><h1>Hello, world!</h1><h2>It is {this.state.date.toLocaleTimeString()}.</h2></div>);}}
这些方法被称作
生命周期钩子。
当组件输出到 DOM 后会执行componentDidMount()钩子,这是一个建立定时器的好地方:componentDidMount() {this.timerID = setInterval(() => this.tick(),1000);}
注意我们是将定时器ID保存在
this中的。
尽管this.props是由React本身安装的以及this.state有特殊的含义,如果你需要存储的东西不在数据流中,你可以随意手动向类中添加其他字段(比如定时器ID)。
我们将在componentWillUnmount()生命周期钩子中卸载计时器:componentWillUnmount() {clearInterval(this.timerID);}
最后,我们实现了每秒钟执行的
tick()方法。
它将使用this.setState()来更新组件局部状态:class Clock extends React.Component {constructor(props) {super(props);this.state = {date: new Date()};}componentDidMount() {this.timerID = setInterval(() => this.tick(),1000);}componentWillUnmount() {clearInterval(this.timerID);}tick() {this.setState({date: new Date()});}render() {return (<div><h1>Hello, world!</h1><h2>It is {this.state.date.toLocaleTimeString()}.</h2></div>);}}ReactDOM.render(<Clock />,document.getElementById('root'));
在 CodePen 中尝试
现在时钟每秒钟都会执行。
让我们快速回顾一下发生了什么以及调用方法的顺序:当
<Clock />被传递给ReactDOM.render()时,React 调用Clock组件的构造函数。 由于Clock需要显示当前时间,所以使用包含当前时间的对象来初始化this.state。 我们稍后会更新此状态。- React 然后调用
Clock组件的render()方法。这是 React 了解屏幕上应该显示什么内容,然后 React 更新 DOM 以匹配Clock的渲染输出。 - 当
Clock的输出插入到 DOM 中时,React 调用componentDidMount()生命周期钩子。 在其中,Clock组件要求浏览器设置一个定时器,每秒钟调用一次tick()。 - 浏览器每秒钟调用
tick()方法。 在其中,Clock组件通过使用包含当前时间的对象调用setState()来调度UI更新。 通过调用setState(),React 知道状态已经改变,并再次调用render()方法来确定屏幕上应当显示什么。 这一次,render()方法中的this.state.date将不同,所以渲染输出将包含更新的时间,并相应地更新DOM。 - 一旦
Clock组件被从DOM中移除,React会调用componentWillUnmount()这个钩子函数,定时器也就会被清除。
正确地使用状态
关于setState()这里有三件事情需要知道不要直接更新状态
例如,此代码不会重新渲染组件:
应当使用// Wrongthis.state.comment = 'Hello';
setState():
构造函数是唯一能够初始化// Correctthis.setState({comment: 'Hello'});
this.state的地方。状态更新可能是异步的
React 可以将多个setState()调用合并成一个调用来提高性能。
因为this.props和this.state可能是异步更新的,你不应该依靠它们的值来计算下一个状态。
例如,此代码可能无法更新计数器:
要修复它,请使用第二种形式的// Wrongthis.setState({counter: this.state.counter + this.props.increment,});
setState()来接受一个函数而不是一个对象。 该函数将接收先前的状态作为第一个参数,将此次更新被应用时的props做为第二个参数:
上方代码使用了箭头函数,但它也适用于常规函数:// Correctthis.setState((prevState, props) => ({counter: prevState.counter + props.increment}));
// Correctthis.setState(function(prevState, props) {return {counter: prevState.counter + props.increment};});
状态更新合并
当你调用setState()时,React 将你提供的对象合并到当前状态。
例如,你的状态可能包含一些独立的变量:
你可以调用constructor(props) {super(props);this.state = {posts: [],comments: []};}
setState()独立地更新它们:
这里的合并是浅合并,也就是说componentDidMount() {fetchPosts().then(response => {this.setState({posts: response.posts});});fetchComments().then(response => {this.setState({comments: response.comments});});}
this.setState({comments})完整保留了this.state.posts,但完全替换了this.state.comments。
