I'm learning react-native and now I'm stucked on state lesson with this error:
_this2.setState is not a function.
Here's the current block of code.
...
export default class StopWatch extends Component {
constructor(props){
super(props);
this.state = {
timeElapsed: null
}
}
handleStartStopClick(){
var startTime = new Date();
setInterval(() => {
this.setState(previousState => {
return {timeElapsed:new Date() - startTime};
});
}, 100);
}
...
What am I doing wrong?
handleStartStopClick
is called from a context where this
is not your class's instance. You can avoid that by adding .bind(this)
to the function you are passing as your click handler.
<TouchableHighlight onPress={this.handleStartStopClick.bind(this)}>
Try this :
this.setState({timeElapsed : (new Date() - startTime)})
You must defined your function in constructor with bind(this) or
handleStartStopClick = () => {...}
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