首页 > 解决方案 > Reactjs momentjs 倒计时天数

问题描述

我想要实现的是,从现在开始对目标日进行倒计时。里面componentDidMount()

nowT = moment(new Date()).format("X"); // => 1603551057 (2020-10-24)
targetDay = moment(result.data.created_at).add('30', 'days').format("X"); // => 1606143175 (2020-11-23)
diffTime = targetDay - nowT; // => 2592000
remain = moment.duration(diffTime, 'milliseconds'); // => {milliseconds: 0, seconds: 11, minutes: 43, hours: 0, days: 0, …}

let intervalId = setInterval(this.countdown(remain), 1000);
this.setState({
  counter: intervalId
});

首先,我得到nowtargetday计算差异,然后将剩余发送到间隔。这是countdown功能:

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,只显示这个静态倒计时,而不是动态的。我做错了什么?

标签: javascriptreactjsmomentjs

解决方案


实际上没有必要计算duration,一旦你得到 和 之间的差异thennow你就可以得到你想要的:

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


推荐阅读