react--页面多个倒计时的setInterval的状态存储

问题描述
首先我们了解一下需求,点击催一催倒计时60s,在不同的问题,不同的标签下,不同的用户倒计时状态不一样。
解决方案
我们一开始在render渲染之前,在componentWillMount周期里面,设置localStorage的key值,然后判断在localStorage里面是否有该key值,有的话,就说明该用户已经被催过,还是在倒计时的状态,点击催一催的时候,利用localStorage记录当前催一催的时间戳,然后刷新页面,在localStorage里面拿到第一次时间戳,let lastTipsTimestamp = localStorage.getItem(cacheKey);利用60 - (moment().unix() - lastTipsTimestamp);获取时间。

componentWillMount() {
        this.intervals = [];
        const users = [];
        let usersLength = 0;
        const tags = [];
        Object.values(this.props.question.usersWithTag).forEach((item)=>{
            tags.push({tag:item.tag,tagId:item.tagId});
            users.push(item.users);
            usersLength += item.users.length;
        });

        this.setState({
            users:users,
            usersLength:usersLength,
            tags:tags
        },()=>{
            this.state.users.forEach((item,key)=>{
                item.forEach((v)=>{
                    let tagId = this.state.tags[key].tagId;
                    let cacheKey= `question-tips-user-${this.props.question.id}-${tagId}-${v.id}`;
                    console.log(cacheKey)
                    if(localStorage.hasOwnProperty(cacheKey))
                    {
                        this.onCountTime(cacheKey,v.id);
                        this.props.addTipByUser(v.id);
                    }
                });
            })
        })
    }

    onCountTime(cacheKey){
        let timer = setInterval(()=>{
            let lastTipsTimestamp =  localStorage.getItem(cacheKey);
            let timeDiff = 60 - (moment().unix() - lastTipsTimestamp);
            if(timeDiff < 1)
            {
                localStorage.removeItem(cacheKey);
                this.intervals.forEach((item)=>{
                    if(item.userCache === cacheKey.substr(19))
                    {
                        clearInterval(item.t);
                        this.forceUpdate();
                    }
                });

            } else
            {
                this.forceUpdate();
            }
        },1000);
        this.intervals.push({
             userCache:cacheKey.substr(19),
             t:timer
        })
    }

    timeToGo(userId,currentTagId){
        let cacheKey= `question-tips-user-${this.props.question.id}-${currentTagId}-${userId}`;
        if(!localStorage.hasOwnProperty(cacheKey))
        {
            localStorage.setItem(cacheKey,moment().unix());
            this.onCountTime(cacheKey,userId);
            this.props.addTipByUser(userId);
        }
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值