Answer the question
In order to leave comments, you need to log in
Why is the function not called the first time?
Good afternoon, I'm just starting to learn React.js and was trying to make a timer, so don't judge too harshly. I had such a problem. When you click on the "set" button, a function is called setTimer()
that should set the value on the dial, but the values \u200b\u200bare not set the first time, I have to click one more time for a successful installation. Please tell me how to fix this error.
Link to sandbox
class App extends Component{
constructor(){
super();
this.state = {
sec: 0,
finalSeconds: 0,
finalMinutes: 0,
};
}
setTimer(){
let input = document.getElementById("input_timer").value;
let param = parseInt(input);
console.log(param);
this.setState({
sec: param,
});
this.countTime();
console.log(this.state.sec);
}
runTimer(){
let input = document.getElementById("input_timer").value;
let param = parseInt(input);
setTimeout(this.decrement.bind(this, param), 1);
}
decrement(data){
console.log(data);
this.setState({
sec: data - 1,
});
console.log("cостояние секунды", this.state.sec);
if(this.state.sec > 0) {
setTimeout(this.decrement.bind(this, this.state.sec), 1000)
}
this.countTime();
};
countTime(){
let secondsForVal = this.state.sec % 60;
let minutesForVal = Math.floor(this.state.sec / 60);
if(secondsForVal.toString().length < 2){
secondsForVal = '0' + secondsForVal.toString();
}
if(minutesForVal.toString().length < 2){
minutesForVal = '0' + minutesForVal.toString();
}
this.setState({
finalSeconds: secondsForVal,
finalMinutes: minutesForVal,
});
}
render(){
return(
<div className="App">
<div className="input_timer"><input type="text" className="input_value" id="input_timer"/></div>
<div className="timer">
<div className="minutesBlock">{this.state.finalMinutes}:</div>
<div className="secondsBlock">{this.state.finalSeconds}</div>
</div>
<button onClick={this.runTimer.bind(this)}>Запустить</button>
<button onClick={this.setTimer.bind(this)}>Установить</button>
</div>
);
}
}
export default hot(module)(App);
Answer the question
In order to leave comments, you need to log in
Everything is called.
The state is not updated immediately after the setState call. So when you call the setState and countTime methods in succession in the setTimer method, the latter deals with the old value state.sec
.
How to achieve the desired behavior... The information you need is in the documentation - run to read .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question