We want to
set up a timer
whenever the
is rendered to the DOM for the first time. This is called "mounting" in React.
我们希望给Class安装一个计时器,可以知道Class什么时候第一渲染到DOM里面。这在React叫做mounting
We also want toclear that timerwhenever the DOM produced by theClock
is removed. This is called "unmounting" in React.
我们也希望当这个Class的node被remove的时候能清除这个计时器。这叫做unmounting。
这些方法叫做生命周期钩子。
componentDidMount() { } 这个钩子在组件输出被渲染到DOM之后run。这里set计时器很好。
componentWillUnmount() { }
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),1000
);
}
注意我们将timerID保存在this里面。
Whilethis.props
is set up by React itself andthis.state
has a special meaning,you are free to add additional fields to the class manually if you need to store something that is not used for the visual output.
尽管this.props由React自己设置,this.state有特殊的意义。我们可以添加其他的filed到class,只要我们需要存储的东西不会用在视觉输出里面。
上面的翻译简直不是人话。意思是
If you don't use something inrender()
,it shouldn't be in the state.
如果我们需要保存的东西不会被用在render()方法中,也就是不会用在视觉输出中,那么这些东西就不应该被保存在state里面。
Finally,we will implement thetick()
method that runs every second.
It will usethis.setState()
to schedule updates to the component local state:
最后我们用this.setState()方法来更新组件本地的state。
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,249)">调用流程:
1.Whenis passed to
ReactDOM.render()
component. Sinceneeds to display the current time,it initializesthis.state
with an object including the current time. We will later update this state.
2.React then calls theClock
component'srender()
method. This is how React learns what should be displayed on the screen. React then updates the DOM to match the's render output.
When theoutput is inserted in the DOM,React calls thecomponentDidMount()
lifecycle hook. Inside it,thecomponent asks the browser to set up a timer to calltick()
once a second.
4.Every second the browser calls thetick()
method. Inside it,theClock
component schedules a UI update by callingsetState()
with an object containing the current time. Thanks to thesetState()
call,React knows the state has changed, and callsmethod again to learn what should be on the screen.
This time,this.state.date
in therender()
method will be different,and so the render output will include the updated time. React updates the DOM accordingly.
5.If thecomponent is ever removed from the DOM,React calls the
componentWillUnmount()
lifecycle hook so the timer is stopped.