Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 反应时间倒数计时(天)_Javascript_Reactjs_Momentjs - Fatal编程技术网

Javascript 反应时间倒数计时(天)

Javascript 反应时间倒数计时(天),javascript,reactjs,momentjs,Javascript,Reactjs,Momentjs,我想要实现的是,从现在开始倒计时到目标日。组件didmount()的内部 首先,我得到now和targetday并计算差值,然后将剩余值发送到interval。下面是倒计时功能: countdown = (r) => { let remain = moment.duration(r - 1000, 'milliseconds'); this.setState({ currentCount: remain.days() + ':' + remain.hours() + &qu

我想要实现的是,从现在开始倒计时到目标日。组件didmount()的内部

首先,我得到
now
targetday
并计算差值,然后将剩余值发送到interval。下面是
倒计时
功能:

countdown = (r) => {
  let remain = moment.duration(r - 1000, 'milliseconds');
  this.setState({
    currentCount: remain.days() + ':' + remain.hours() + ":" + remain.minutes() + ":" + remain.seconds()
  });
  console.log(remain.days() + ':' + remain.hours() + ":" + remain.minutes() + ":" + remain.seconds()); // => 0:0:43:11
}

问题是它返回了错误的倒计时
0:0:43:11
,并且它没有在
render
中更新,只显示这个静态倒计时,而不是动态倒计时。我做错了什么?

您正在调用函数
this.countdown()
,该函数直接返回一个值,而不是在希望传递参数的位置传递函数引用

如果我真的要解释你的代码,你现在要做的是:

//伪代码,仅用作示例
设置间隔(无效,1000)
当你想做的是

//伪代码-仅用作示例
设置间隔(此为倒计时,1000)
//这很好,只要我们不需要传递参数^
基本上,为了做到这一点,您需要将函数作为带有参数的回调传递

setInterval(()=>this.countdown(剩余),1000)

最后,请注意,不要忘记在
组件中
clearInterval()
将卸载()
,否则您的应用程序中可能会出现内存泄漏。

实际上无需计算
持续时间
,一旦您得到
之间的差异,那么
现在
就可以得到您想要的:

this.interval = setInterval(() => {
  nowT = moment();
  targetDay = moment(result.data.created_at).add('30', 'days');
  diffTime = moment(targetDay - nowT);
  timeObj = {
    count_days: diffTime.format('D');
    count_hours: diffTime.format('HH');
    count_minutes: diffTime.format('mm');
    count_seconds: diffTime.format('ss');
  }
}, 1000);

现在,您可以使用
setState
render

中获取重复的值,即使在固定间隔后,也始终使用相同的参数调用它。您需要将所有计算移到
coundown
函数中。您将返回
this.countdown()
的值,而不是传递
this.countdown()的函数引用。countdown
@guy不,我将所有计算移到它中,没有成功,只是为了修复最明显的错误。我不明白你为什么要手动计算所有东西,而你只需要利用瞬间直接得到结果。是的,我已经使用了
clearInterval
。我使用了
setInterval(()=>this.countdown(remaine),1000)
但仍然返回了错误的倒计时。可能是因为您将它放在了
componentDidMount()
中。你需要比“错误倒计时”更具体。这取决于你想要达到的目标
this.interval = setInterval(() => {
  nowT = moment();
  targetDay = moment(result.data.created_at).add('30', 'days');
  diffTime = moment(targetDay - nowT);
  timeObj = {
    count_days: diffTime.format('D');
    count_hours: diffTime.format('HH');
    count_minutes: diffTime.format('mm');
    count_seconds: diffTime.format('ss');
  }
}, 1000);