【发布时间】:2020-04-09 22:48:58
【问题描述】:
我的代码旨在启动一个 20 分钟 -> 20:00 的计时器。我似乎在代码中遗漏了一些东西。当我在 Timer() 中调用它时,我的 setState 没有改变 time 的值:
class Sleep extends Component {
// create constructor to get access to props
constructor(props) {
super(props);
this.state = {
time: 1200,
timer: '',
};
}
componentDidMount() {
this.interval = setInterval(this.Timer(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
Timer() {
console.log('time is ' + this.state.time);
this.setState({
time: this.state.time - 1,
});
console.log('time is ' + this.state.time);
var timer;
var minutes = Math.floor(this.state.time / 60);
var seconds = this.state.time % 60;
if (minutes < 10) {
minutes = '0' + minutes.toString();
}
if (seconds < 10) {
seconds = '0' + seconds.toString();
}
timer = minutes.toString() + ':' + seconds.toString();
this.setState({
timer: timer,
});
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#FFFFFF', paddingBottom: 100 }}>
<View>
<Text style={styles.timerText}>{this.state.timer}</Text>
</View>
</View>
);
}
}
计时器应该每秒从 20:00 倒计时到 00:00。我输入了一些 console.log() 语句来尝试诊断问题。
【问题讨论】:
-
也许这会对你有所帮助stackoverflow.com/questions/31963803/…
标签: javascript reactjs timer native