Champer Wu
Champer Wu

Reputation: 1271

ReactJs state change and value is not what I want

I try to build a calendar app to practise.

In the state I have a current_month: 1, and I have a function IncreaseMonth() to increase current_month but when current_month value becomes 12, I want it changed to 1.

I try to use componentWillUpdate() lifecycle method to do it, in the code below:

componentWillUpdate(prev, next) {
   if (next.current_month == 13) {
     this.setState({current_month: 1})
   }
}

But I watch tutorials about lifecycle, which tell me not to use componentWillUpdate() to set state.

Is there a better way to do this?

Upvotes: 0

Views: 57

Answers (1)

Sajith Edirisinghe
Sajith Edirisinghe

Reputation: 1727

The correct way would be to move reseting month value into IncreaseMonth() method as shown below.

IncreaseMonth = () => {
  let month = 1;
  if (this.state.current_month < 12) {
    month = this.state.current_month + 1;
  }
  
  this.setState({
    current_month: month
  });
}

You MUST not set the state in componentWillUpdate() lifecycle event as that event is triggered to indicate that the component is going to be re-rendered, and you can decide within this method whether the component should continue with re-rendering. If this method returns true, the component will be re-rendered. For more information, refer the official documentation

Upvotes: 3

Related Questions