React中使用setInterval函數(shù)的實(shí)例
本文是基于Windows 10系統(tǒng)環(huán)境,學(xué)習(xí)和使用React:Windows 10
一、setInterval函數(shù)
(1) 定義
setInterval() 方法可按照指定的周期(以毫秒計(jì))來(lái)調(diào)用函數(shù)或計(jì)算表達(dá)式。
setInterval() 方法會(huì)不停地調(diào)用函數(shù),直到 clearInterval() 被調(diào)用或窗口被關(guān)閉。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的參數(shù)。
(2) 實(shí)例
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ù)的實(shí)例的文章就介紹到這了,更多相關(guān)React中使用setInterval函數(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React-Route6實(shí)現(xiàn)keep-alive效果
本文主要介紹了React-Route6實(shí)現(xiàn)keep-alive效果,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧<BR>2022-06-06
Yarn安裝項(xiàng)目依賴(lài)報(bào)error?An?unexpected?error?occurred:?“XXXXX:E
這篇文章主要為大家介紹了Yarn安裝項(xiàng)目依賴(lài)報(bào)error?An?unexpected?error?occurred:?“XXXXX:ESOCKETTIMEOUT”問(wèn)題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
React報(bào)錯(cuò)之組件不能作為JSX組件使用的解決方法
本文主要介紹了React報(bào)錯(cuò)之組件不能作為JSX組件使用的解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
React + Node.js實(shí)現(xiàn)圖片上傳功能
最近筆者在開(kāi)發(fā)個(gè)人博客的后臺(tái)管理系統(tǒng),里面用到了圖片上傳相關(guān)的功能,在這里記錄并分享一下,希望可以幫到大家,話不多說(shuō)直接開(kāi)始吧,感興趣的朋友可以參考下2024-01-01
React Hook useState useEffect componentD
這篇文章主要介紹了React Hook useState useEffect componentDidMount componentDidUpdate componentWillUnmount問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03

