本文是基于Windows 10系統(tǒng)環(huán)境,學(xué)習(xí)和使用React:Windows 10
一、setInterval函數(shù)
(1) 定義
setInterval() 方法可按照指定的周期(以毫秒計)來調(diào)用函數(shù)或計算表達式。
setInterval() 方法會不停地調(diào)用函數(shù),直到 clearInterval() 被調(diào)用或窗口被關(guān)閉。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的參數(shù)。
(2) 實例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
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; |
到此這篇關(guān)于React中使用setInterval函數(shù)的實例的文章就介紹到這了,更多相關(guān)React中使用setInterval函數(shù)內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/qq_32599479/article/details/104037774