问题描述
首先我们了解一下需求,点击催一催倒计时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);
}
}