我尝试构建一个日历应用程序来练习。
在该状态下,我有一个 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,则组件将被重新渲染。欲了解更多信息,请参阅official documentation
关于javascript - ReactJs状态变化和值不是我想要的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47496177/