React中使用setInterval函数的实例

2022-04-15 0 454

本文是基于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;

到此这篇关于React中使用setInterval函数的实例的文章就介绍到这了,更多相关React中使用setInterval函数内容请搜索NICE源码以前的文章或继续浏览下面的相关文章希望大家以后多多支持NICE源码!

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 JavaScript React中使用setInterval函数的实例 https://www.niceym.com/32697.html