React中如何使用setInterval函数

React中如何使用setInterval函数

本文是基于Windows 10系统环境,学习和使用React:

  • Windows 10

一、setInterval函数

(1) 定义

setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。
setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的参数。

(2) 实例

import React, { Component } from 'react';
import { Radio, Button, Icon } from 'antd';

class List extends Component {
    constructor(props) {
        super(props);
        this.state = {
            online: false,
        };
    };

    handleLogin=()=>{
        localStorage.setItem('username','xuzheng');
    };

    handleLogout=()=>{
        localStorage.removeItem('username');
    };

    componentDidMount(){
        this.timer = setInterval(() => {
            this.setState({
                online: localStorage.username ? true : false,
            })
        }, 1000);
    }

    componentWillUnmount() {
        if (this.timer != null) {
            clearInterval(this.timer);
        }
    }

    render() {
        return (
            <div>
                <div>
                    <Icon type='user' style={{marginRight:'8px'}}/>
                    <span>{localStorage.username ? localStorage.username : '未登录'}</span>
                </div>
                <div style={{marginTop:'20px'}}>
                    <Button type='primary' onClick={this.handleLogin}>登录</Button>
                </div>
                <div style={{marginTop:'20px'}}>
                    <Button type='primary' onClick={this.handleLogout}>退出</Button>
                </div>
            </div>
        )
    }
}

export default List;


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值