Reactjs momentjs 天数倒计时

Reactjs momentjs countdown in days

我想要实现的是,从现在开始为目标日期倒计时。 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
}

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

您正在直接调用 this.countdown() 函数 returns 一个值 ,而不是在您希望传递参数的地方传递函数引用.

如果我从字面上解释你的代码,你现在正在做的是:

// pseudo-code, serves only as example
setInterval(void, 1000)

当您想做的事情是

// pseudo-code - serves only as example
setInterval(this.countdown, 1000)
// this is fine as long as we don't have to pass arguments ^

基本上,为了做到这一点,您需要将函数作为带有参数的回调传递

setInterval(() => this.countdown(remain), 1000)

最后一点,不要忘记在 componentWillUnmount()clearInterval() 否则您的应用程序可能会发生内存泄漏。

其实不需要计算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

中的值