I was working with react.js and I added this.setState() in the constructor but it doesnt work.
Here is my code -
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
age: '18'
}
this.setState({id: 'name'});
}
render(){
return (
<div>
<p>{this.state.id}</p>
<p>{this.state.value}</p>
</div>
)
}
}
This renders the second p tag but not the first why so?
Don't use setState() inside constructor or inside render method
constructor- is called once when the instance is created if you create inside constructor rerendering won't happen.
render - if you use setState() inside the render method it will go to infinite because re-rendering happens when you use setState()
if you want to save such property to state do it inside lifecycle method componentDidMount()
Improved
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
age: '18'
}
}
componentDidMount(){
this.setState({id: 'name'});
}
render(){
return (
<div>
<p>{this.state.id}</p>
<p>{this.state.value}</p>
</div>
)
}
}
or directly put as you did for age
this.state = {
age: '18',
id: 'name'
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With