React倒计时

在开发中,我们常会遇到倒计时的需求,今天用 react 写一个倒计时,实现在某个系统中,定时检验 token 是否有效,适用于试用帐户等场景。

代码很简单,只不过要注意区分 React 的生命周期,在组件未挂载的时候,也就是componentWillMount生命周期中,发送请求,并添加相应的响应拦截。在componentDidMount生命周期中不断发送请求,在componentWillUnmount生命周期中clearInterval

直接上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
export class Dashboard extends React.Component {
constructor(props) {
super(props);
this.state = {
intervalId: null,
currentCount: 20,
};
this.timer = this.timer.bind(this);
}
componentWillMount() {
const code = window.location.href.substring(
window.location.href.indexOf('=') + 1
);
const tokenAndTime = Base64.decode(code);
const token = tokenAndTime.split('+')[0];
localStorage.setItem('token', token);
axios.interceptors.response.use(
(response) => {
return response;
},
(error) => {
if (error.response) {
switch (error.response.status) {
case 401:
// 返回 401 清除token信息并跳转到登录页面
window.location.href = '#';
}
}
return Promise.reject(error.response.data); // 返回接口返回的错误信息
}
);
axios({
method: 'get',
url: `#`,
headers: { token: token },
}).then((response) => {
if (response.data.code === 200) {
console.log('登录成功');
localStorage.setItem('name', response.data.data.name);
localStorage.setItem('teacher', response.data.data.teacherName);
} else {
console.log('登录失败');
}
});
}
componentDidMount() {
var intervalId = setInterval(this.timer, 3000000);
this.setState({ intervalId: intervalId });
}
componentWillUnmount() {
clearInterval(this.state.intervalId);
}
timer() {
const storage = window.localStorage;
var newCount = this.state.currentCount - 1;
if (newCount >= 0) {
axios({
method: 'get',
url: `#`,
headers: { Authorization: storage.token },
}).then((response) => {
if (response.data.code === 200) {
console.log('token有效');
} else {
console.log('token失效');
window.location.href = '#';
}
});
this.setState({ currentCount: newCount });
} else {
clearInterval(this.state.intervalId);
}
}
}
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2018-2020 Jee
  • Visitors: | Views:

如果您觉得此文章帮助到了您,请作者喝杯咖啡吧~

支付宝
微信