首页 > 解决方案 > 如何以功能方式使用钩子更新我的反应组件

问题描述

我想制作一个简单的时钟,每秒更新一次我真的很陌生,所以我有点困惑如何在函数中使用钩子我正在尝试这个现在卡在如何更新 setTimer 并在返回函数中显示更新提前谢谢

import React, { useState } from 'react';

function Timer() {

    const [timer, setTimer] = (useState(new Date().toLocaleTimeString()));
    return (

        <div>
            <h2>It is {timer}.</h2>
        </div>
    )
}

export default Timer

标签: reactjs

解决方案


你可以使用useEffect钩子,

useEffect(()=>{
    //This will update timer every second
    const interval = setInterval(()=>{
      setTimer(new Date().toLocaleTimeString())
    },1000); 

    //This is important to clear interval
    return () => clearInterval(interval)
},[timer]) //Dependency array, useEffect will run only when timer changes

演示


推荐阅读