React中使用setInterval函数 React中使用setInterval函数的实例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

React中使用setInterval函数 React中使用setInterval函数的实例

哈工大的许政   2021-04-06 我要评论
想了解React中使用setInterval函数的实例的相关内容吗,哈工大的许政在本文为您仔细讲解React中使用setInterval函数的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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;

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们