React中使用setInterval函数的实例

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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;

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

脚本宝典总结

以上是脚本宝典为你收集整理的React中使用setInterval函数的实例全部内容,希望文章能够帮你解决React中使用setInterval函数的实例所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:React