javascript - 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
});
首先,我得到now
并targetday
计算差异,然后将剩余发送到间隔。这是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
,只显示这个静态倒计时,而不是动态的。我做错了什么?
解决方案
实际上没有必要计算duration
,一旦你得到 和 之间的差异then
,now
你就可以得到你想要的:
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
推荐阅读
- amazon-web-services - 如何将远程桌面用户限制为 Windows Server 2016 上的单个应用程序?
- php - Php Doctrine:如何避免 DQL 中的完整限定实体名称
- sql - MS Access VBA - SQL 从表单文本框中检索数据
- python - 在数据块中加载 json 响应以触发数据帧时获取 _corrupt_record
- r - 有没有办法通过将一列单词与 R 中的一列句子匹配来合并
- javascript - HighCharts 显示不同 PC 上同一图表的两个不同实例
- java - JVM的虚函数查找对final有什么优化吗?
- java - 使用 Criteria API 加入实体,关系仅在拥有方定义
- r - 制作一个 ggpaired 图,其中 line.color 是加权函数?
- ios - 由于 Swift 中的 AddSubview,呈现新视图会导致崩溃