ahadortiz
ahadortiz

Reputation: 1166

How to initialize state in componentWillReceiveProps lifecycle for React16.x?

I used to initialize state in componentWillReceiveProps using this.state = ... By the way, it's deprecated in React16.x It's recommended to use this.setState instead of this.state = . But I have to initialize state in componentWillReceiveProps, because some old states remains if I use this.setState function. Do you have any idea? Please advise me. Thanks

Upvotes: 1

Views: 307

Answers (2)

random-forest-cat
random-forest-cat

Reputation: 35954

The problem is that you are initializing state in one of the lifecycle methods - you only want to do this in the constructor.

Typically, you'd initialize state in the constructor, or with setInitialState

constructor() {
  this.state = { foo: 'bar' }
}

componentWillReceiveProps() {
  this.setState({ foo: 'baz' })
}

From there, you can call setState in your lifecycle methods.

For initializing state, you would use this.state = {} in the constructor, and for updating state call this.setState().


Also, you mentioned this...

By the way, it's deprecated in React16.x It's recommended to use this.setState instead of this.state =

Can you point me to where you see this in the documentation? According to https://reactjs.org/blog/2017/09/26/react-v16.0.html#breaking-changes there are some changes to the way setState behaves in the context of react lifecycle methods, but I haven't found anything to validate your claim

Upvotes: 2

tekna
tekna

Reputation: 3

Whenever you're defining any method in reactjs, do it this way:

increment: function(){
       this.setState({
        count: this.state.count + 1
       })
     }

// I'm adding something to the previous state of count here.

Upvotes: 0

Related Questions