最近有一个需求是做一个闪购列表,列表中每一个商品都有倒计时,如果每一个倒计时都去生成一个setTimeout的话,一个页面就会有很多定时器,感觉这种做法不是非常好,于是换了一个思路。

思路是这样的,一个页面只生成一个定时器。页面利用对象去维护一个回调函数列表,key可以是id等唯一标识,value就是更新时间的函数,我这里用的是setState。提供一个往对象里添加回调函数的方法和一个移除回调函数的方法。

// 用于存放每个倒计时的回调方法
const countDownFuncList = {}; const addFunc = (key, func) => {
countDownFuncList[key] = func;
}
const removeFunc = (key) => {
delete countDownFuncList[key];
}

生成一个定时器,隔一定的时间就去遍历回调函数列表,调用里面的函数。

let intervalHandler = -1;
const countDown = () => {
if (intervalHandler !== -1) {
clearTimeout(intervalHandler);
}
intervalHandler = setTimeout(() => {
const now = new Date();
Object.keys(countDownFuncList).forEach((key) => {
const item = countDownFuncList[key];
if (typeof item === 'function') {
item(now);
}
})
}, 300);
}  

具体调用是调用timeContent方法来处理展示的时间。

const timeContent = (millisecond) => {
const second = millisecond / 1000;
let d = Math.floor(second / 86400);
let h = Math.floor((second % 86400) / 3600);
let m = Math.floor(((second % 86400) % 3600) / 60);
let s = Math.floor(((second % 86400) % 3600) % 60); let countDownDOM;
if (d > 0) {
countDownDOM = (<div class="count-down">{d} 天 {h} : {m} : {s}</div>);
} else {
countDownDOM = (<div class="count-down">{h} : {m} : {s}</div>);
} return countDownDOM;
}

这个方法有一个缺点就是当前时间的获取,除了初始化步骤以外,之后的更新都是通过new Date()来获取的,这样存在获取的时间可能并不是正确的当前时间的问题。

完整代码如下:

// 用于存放每个倒计时的回调方法
const countDownFuncList = {}; const addFunc = (key, func) => {
countDownFuncList[key] = func;
}
const removeFunc = (key) => {
delete countDownFuncList[key];
} const timeContent = (millisecond) => {
const second = millisecond / 1000;
let d = Math.floor(second / 86400);
let h = Math.floor((second % 86400) / 3600);
let m = Math.floor(((second % 86400) % 3600) / 60);
let s = Math.floor(((second % 86400) % 3600) % 60); let countDownDOM;
if (d > 0) {
countDownDOM = (<div class="count-down">{d} 天 {h} : {m} : {s}</div>);
} else {
countDownDOM = (<div class="count-down">{h} : {m} : {s}</div>);
} return countDownDOM;
} let intervalHandler = -1;
const countDown = () => {
if (intervalHandler !== -1) {
clearTimeout(intervalHandler);
}
intervalHandler = setTimeout(() => {
const now = new Date();
Object.keys(countDownFuncList).forEach((key) => {
const item = countDownFuncList[key];
if (typeof item === 'function') {
item(now);
}
})
}, 300);
} countDown(); class CountDownItem extends React.Component {
constructor(props) {
super(props);
this.state = {
currentTime: this.props.nowDate
} this.parseDisplayTime = this.parseDisplayTime.bind(this);
} componentDidMount() {
const { id } = this.props;
// 往事件列表添加回调函数
addFunc(id, this.updateTime);
} componentWillUnmount() {
const { id } = this.props;
// 从事件列表移除回调函数
removeFunc(id);
} updateTime(time) {
this.setState({
currentTime: time
})
} parseDisplayTime() {
const { endTime, id } = this.props;
const { currentTime } = this.state;
const subtractTime = endTime - currentTime;
let countDownDOM = '';
if(subtractTime > 1000){
countDownTimeDOM = (
<div className="count-down-content">
{timeContent(subtractTime)}
</div>
);
}else{
removeFunc(id);
} return countDownDOM;
} render(){
return(
<div className="count-down-wrap">{this.parseDisplayTime()}</div>
);
}
}

React中需要多个倒计时的问题的更多相关文章

  1. react中简单倒计时跳转

    其实在react中实现倒计时的跳转方法有很多中,其中我认为较为好用的就是通过定时器更改state中的时间值. 首先在constructor中设置10秒的时间值: constructor () { su ...

  2. 理解React中es6方法创建组件的this

    首发于:https://mingjiezhang.github.io/(转载请说明此出处). 在JavaScript中,this对象是运行时基于函数的执行环境(也就是上下文)绑定的. 从react中的 ...

  3. 【原】React中,map出来的元素添加事件无法使用

    在使用react中,经常用到react的map函数,用法和jquery里中的map一样,但是,如果你在每个map出来的元素中添加,你会发觉添加的事件无法关联, 比如,我们很多的评论,我需要在每个评论下 ...

  4. React中props.children和React.Children的区别

    在React中,当涉及组件嵌套,在父组件中使用props.children把所有子组件显示出来.如下: function ParentComponent(props){ return ( <di ...

  5. Immutable 详解及 React 中实践

    本文转自:https://github.com/camsong/blog/issues/3 Shared mutable state is the root of all evil(共享的可变状态是万 ...

  6. React中父组件与子组件之间的数据传递和标准化的思考

    React中父组件与子组件之间的数据传递的的实现大家都可以轻易做到,但对比很多人的实现方法,总是会有或多或少的差异.在一个团队中,这种实现的差异体现了每个人各自的理解的不同,但是反过来思考,一个团队用 ...

  7. React中使用CSSTransitionGroup插件实现轮播图

    动画效果,是一个页面上必不可少的功能,学习一个新的东西,当然就要学习,如何用新的东西,用它的方法去实现以前的东西啦.今天呢,我就在这里介绍一个试用react-addons-css-transition ...

  8. 在React中使用Redux

    这是Webpack+React系列配置过程记录的第六篇.其他内容请参考: 第一篇:使用webpack.babel.react.antdesign配置单页面应用开发环境 第二篇:使用react-rout ...

  9. React中的路由系统

    React中的路由系统 提起路由,首先想到的就是 ASPNET MVC 里面的路由系统--通过事先定义一组路由规则,程序运行时就能自动根据我们输入的URL来返回相对应的页面.前端中的路由与之类似,前端 ...

随机推荐

  1. hdu 1520 树形DP基础

    http://acm.hdu.edu.cn/showproblem.php?pid=1520 父节点和子节点不能同时选. http://blog.csdn.net/woshi250hua/articl ...

  2. gsap

    TweenMax借助于css,轻量级的js库 下面是简单的demo <!DOCTYPE html> <html lang="en"> <head> ...

  3. GitHub网页端和客户端操作

    参见GitHub上的repository中的moreLove.tata.tata2 moreLove 在网页版GitHub上创建的空项目然后填充的tata 在windows客户端创建的空项目然后填充的 ...

  4. spark编程python实例

    spark编程python实例 ValueError: Cannot run multiple SparkContexts at once; existing SparkContext(app=PyS ...

  5. 刚在虚拟机上装的Linux系统,ifconfig后IP地址怎么成了127.0.0.1了

    之前在虚拟机上装了Linux系统,用了一段时间后想删除了重新装一下,然而装完以后ifconfig后,出现的是 [root@localhost ~]# ifconfig lo Link encap:Lo ...

  6. ubuntu14.04安装rabbitmq

      ubuntu14.04安装rabbitmq及配置 1.修改/etc/apt/sources.list文件 命令:vi /etc/apt/sources.list 在最后一行加上:deb http: ...

  7. GitHub无法push的问题

    问题背景 换了台别人用过的电脑想要将文件push到github上,出现下面报错 remote: Permission to *****(我的)/gittest.git denied to *****( ...

  8. SharePoint中遇到Timeout

    使用SharePoint时会遇到不止一种的timeout(即超时)错误. 如果遇到了timeout, 该怎么区分呢? 大致上SharePoint可以控制和影响的timeout地方如下: 1. Shar ...

  9. (原创)攻击方式学习之(3) - 缓冲区溢出(Buffer Overflow)

    堆栈溢出 堆栈溢出通常是所有的缓冲区溢出中最容易进行利用的.了解堆栈溢出之前,先了解以下几个概念: 缓冲区 简单说来是一块连续的计算机内存区域,可以保存相同数据类型的多个实例. 堆栈     堆 栈是 ...

  10. 三个方法教会你win7中IIS7配置php环境

    三个方法教会你win7中IIS7配置php环境.今天静下心来研究了下在win7中使用IIS7配置php环境,其实很简单!跟下面方法做之前,请先确定你的电脑中未安装其它相关环境程序及服务,之前安装过ap ...