我尝试构建一个日历应用程序进行练习。
在状态下,我有一个current_month: 1
,并且我有一个函数IncreaseMonth()
可以增加current_month
,但是当current_month
值变为12时,我希望它更改为1。
我尝试使用componentWillUpdate()
生命周期方法来执行此操作,在下面的代码中:
componentWillUpdate(prev, next) {
if (next.current_month == 13) {
this.setState({current_month: 1})
}
}
但我观看了有关生命周期的教程,告诉我不要使用componentWillUpdate()
设置状态。
有更好的方法吗?
正确的方法是将重置月值移动到IncreaseMonth()
方法中,如下所示。
IncreaseMonth = () => {
let month = 1;
if (this.state.current_month < 12) {
month = this.state.current_month + 1;
}
this.setState({
current_month: month
});
}
您不得在componentwillupdate()生命周期事件中设置状态,因为触发该事件以表明要重新渲染组件,并且可以在此方法中确定组件是否应继续重新渲染。如果此方法返回true,则将重新渲染组件。有关更多信息,请参阅官方文档