React中使用setInterval函數(shù)的實例
本文是基于Windows 10系統(tǒng)環(huán)境,學(xué)習(xí)和使用React:Windows 10
一、setInterval函數(shù)
(1) 定義
setInterval() 方法可按照指定的周期(以毫秒計)來調(diào)用函數(shù)或計算表達(dá)式。
setInterval() 方法會不停地調(diào)用函數(shù),直到 clearInterval() 被調(diào)用或窗口被關(guān)閉。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的參數(shù)。
(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;
到此這篇關(guān)于React中使用setInterval函數(shù)的實例的文章就介紹到這了,更多相關(guān)React中使用setInterval函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
全棧輕量級搭配之Remix Prisma Sqlite使用分析
這篇文章主要為大家介紹了全棧輕量級搭配之Remix Prisma Sqlite使用示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05使用ReactJS實現(xiàn)tab頁切換、菜單欄切換、手風(fēng)琴切換和進(jìn)度條效果
這篇文章主要介紹了使用ReactJS實現(xiàn)tab頁切換、菜單欄切換、手風(fēng)琴切換和進(jìn)度條效果的相關(guān)資料,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2016-10-10React Hook 'useEffect' is call
這篇文章主要為大家介紹了React Hook 'useEffect' is called in function報錯解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12react-redux的connect與React.forwardRef結(jié)合ref失效的解決
這篇文章主要介紹了react-redux的connect與React.forwardRef結(jié)合ref失效的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05React中組件的this.state和setState的區(qū)別
在React開發(fā)中,this.state用于初始化和讀取組件狀態(tài),而setState()用于安全地更新狀態(tài),正確使用這兩者對于管理React組件狀態(tài)至關(guān)重要,避免性能問題和常見錯誤2024-09-09詳解React Native開源時間日期選擇器組件(react-native-datetime)
本篇文章主要介紹了詳解React Native開源時間日期選擇器組件(react-native-datetime),具有一定的參考價值,有興趣的可以了解一下2017-09-09create-react-app全家桶router?mobx全局安裝配置
這篇文章主要為大家介紹了create-react-app全家桶router?mobx全局安裝配置,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06