I am trying to setState from previous Props using, now, the deprecated componentWillReceiveProps like below
componentWillReceiveProps(props) {
this.setState({
temp: Math.round(((props.weather.temp-273.15)*1.8)+32)
})
console.log(this.state)
}
The problem I am facing is when I do this, when the app updates, the state is NaN for 1 second before becoming the correct number.
I tried using componentWillMount(){} instead, but not only is that not a good lifecycle to use for setting state, the previous props are not available during this time
How can I prevent this NaN from appearing in the rendered DOM and only show the state?
EDIT
You are all correct. I was more concerned with whether there should be a lifecycle or React specific handler to resolve this kinda issue. I guess it's true that React is mostly comprised of plain ol' javascript.
You can render the element only if it has value:
{ this.state.temp && <div>{this.state.temp}</div>}
This will not allow to render NaN
.
You may know Boolean(NaN)
returns false. So, the above expression will return false if the value is currently NaN
and will not process further.