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;


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章