reactjs - 承诺中的 setInterval,在 React 中只执行一次
问题描述
我正在尝试创建一个倒数计时器,每秒滴答一秒。间隔只工作一次,不执行。问题是在进行服务器调用之前我没有this.state.timetill ,然后我可以开始计时器。因此,setInterval 函数必须隐藏在一个 Promise 中,它只执行一个。然而,timetill 变量可以是一个常量,一旦检索到它就不会改变。
componentDidMount = async () => {
const that = this;
*do stuff*
this.someFunction().finally(() => {
/*This right here, below is not working */
setInterval(that.createTimer(), 1000);
});
}
我的 JSX 就是这样
{this.state.setTimer}
有问题的函数,时间必须除以 1000,因为 javascript 使用毫秒
createTimer = async timerNow => {
var timerNow = (await new Date().getTime()) / 1000;
// Find the distance between now and the count down date
var distance = this.state.timeTill - timerNow;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
//the variable displayed
var setTimer = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
this.setState({setTimer});
};
解决方案
createTimer
您传递to的返回值setInterval
,而不是传递函数但不调用它
setInterval(this.createTimer, 1000)
推荐阅读
- python - 使用神经网络的传播模型(我是初学者)
- php - 如何在php中包含“<”符号的dom解析器html表
- laravel - 在 laravel 图表中找不到类 'ConsoleTVs\Charts\Facades\Charts'
- python-3.x - For 循环和 if 条件
- python-3.x - 根据其他列的相对大小为列分配值
- java - 在java中使用正则表达式计算文件
- java - Java BMICalculator 无法按预期工作
- vim - MacVim 中的重复状态行
- java - 错误的返回类型/扫描仪
- google-sheets - 试图找到一种方法在不触发 3 行差异的情况下在谷歌电子表格中复制我的公式