Consider the program below, when it is run in its current form it never displays "here" to the screen however if the fourth line is commented out then it does. it is my understanding that setState is asynchronous however I would imagine that when var is eventually set to true the while loop will end.
To be clear, this is how I understand what is happening:
The component is created, immediately componentDidMount
is called, then this.setState({var: true})
is called. This is done asynchronously so the program splits into two "paths", the first continues on to the while loop where it gets stuck, the second changes var from false to true. Once var is changed from false to true the the first path should break out of the while loop and the second path should end because the asynchronous call is complete. However this is not what happens which is what I find confusing.
export default class Test extends Component {
constructor(props){
super(props)
this.state = {var: false}; // consider removing this line
}
componentDidMount(){
this.setState({var: true})
while (this.state.var == false){}
}
render(){
return(<View style={{padding: 30}}><Text>Here</Text></View>)
}
}
Thanks for the help