以下是react生命周期钩子的官方案例,下面这个案例,如果我稍作改动,把setInterval 改成 setTimeout放在render() 里面,这样setTimeout 会setState, 然后循环call render(), 循环setTimeout. 也可以实现,那么这种情况用生命周期钩子为什么是必须的,或者有什么好处呢? 为了代码整洁? 为了减少memory消耗??
原官方案例
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
this.setState({
date: new Date()
}), 1000);
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
我的改动
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
render() {
this.timerID = setTimeout(
this.setState({
date: new Date()
}),1000);
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
你这样如果有其他的
state
更新,就有多个timeout
定时器,即使你在set
前clear
一下,其他的渲染也会重新触发render
来导致上一个被清空,所有你的这个方案很简陋,不能拿一个没有应用场景的例子来打败一个官方示例/常用方案不过单从你这个例子,在前提是整个程序只有这一个组件,整个组件只有一个
state
,并且没有其他任何东西影响的情况,是可以的,在setTimeout
之前clear
一下更稳妥一点