I have a react-native class component, in which I have a counter function:
counter() {
console.log("hi")
this.setState({count:this.state.count+1})
}
I have a state named count initialized to 0. I have a text which displays the count value as well.
In my render, in the return, im trying to call this counter function onPress of a TouchableOpacity. I tried 2 things in the onPress with 2 different outputs. Can someone explain why i got these outputs for each case? :
here, state value was updating and displaying, and i got the console.log as well (desired output)
here, i got the console.log, but the state value wasn't updating. why isnt state updating here?
Thanks in advance
If you want to call counter function without arrow pattern in class component then you need to call bind in constructor block for counter function
constructor(props) {
super(props);
this.counter = this.counter.bind(this);
}
counter() {
this.setState({ count: this.state.count + 1 });
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.