1
The problem is this: I’m trying to build an accountant to practice mine React
and an error occurred:
this is undefined
I created a state to hold the minutes and seconds:
constructor(props) {
super(props)
this.state = {
min: 0,
seg: 0,
}
}
I called you both there to my surrender:
render() {
const { min, seg } = this.state;
return (
<React.Fragment>
<p>{min}:{seg}</p>
<button onClick={this.startCountdown}>Start</button>
<button>Stop</button>
<button>Reset</button>
</React.Fragment>
)
}
and then and went to create the function to start counting. Look, at first I don’t want the logic of decrementation, I was trying to simply change the values on the screen by clicking on startCowndown
, but I had the return of error this is undefined
.
My function to change the values on the screen was like this:
startCountdown () {
let {min, seg} = this.state;
this.setState({min: 1, seg: 59})
}
Well, it didn’t work, so I thought it would be unnecessary to call min and seg with the destructuring since I was already using the method setState
, so I took.
startCountdown(){
this.setState({min: 1, seg: 59})
}
and yet this is Undefined continues to appear.
Could someone explain to me why this behavior?
missing Arrow Function.
<button onClick={() => this.startCountdown}>Start</button>
and in the methodstartCountdown () => {...
– Marconi
and another need not do the descruct, correct method
startCountdown () => {
 this.setState({min: 1, seg: 59})
}
– Marconi
Take a look with Hooks https://codesandbox.io/s/epic-hugle-hq4x5
– Marconi
your solutions are perfect, but none of them worked or would even work, precisely because I was calling the onClick function not in a tag, but in the Button component. <Button onClick={startPomodoro}/> After I made the call inside the tag all the presented solutions started to work.
– Antônio Matheus
what contradiction.
– novic