import React,{Component} from "react";
class Message extends Component{
constructor()
{
super()
this.state={
message:0
}
}
changemessage()
{
this.setState(
prevState=>({
message:prevState.message+1
}
),
()=>
{
console.log( 'callback value',this.state.message)
}
)
}
sample()
{
this.setState(
prevState=>({
message:this.state.message+1
}
),
()=>
{
console.log( 'callback value',this.state.message)
}
)
}
convert()
{
this.changemessage()
this.sample()
this.changemessage()
this.sample()
this.changemessage()
this.sample()
this.changemessage()
this.sample()
this.changemessage()
}
render()
{
return(
<div>
<h1 >{this.state.message}</h1>
<button onClick={()=>{this.convert()}}>Subscribe</button>
</div>
)
}
}
To understand the SetState i used two function with prev state and this.state.I expect 9 as answer .but i get 2 as a answer printed in console for 9 times.if i use Prev State in both function instead of this.state.message in sample function i got 9 as a answer.i want to know what happening in the background if i use like this.