reactjs - 如何以功能方式使用钩子更新我的反应组件
问题描述
我想制作一个简单的时钟,每秒更新一次我真的很陌生,所以我有点困惑如何在函数中使用钩子我正在尝试这个现在卡在如何更新 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
解决方案
你可以使用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
推荐阅读
- java - 约束数组列表的所有组合
- php - 更新查询未在 MySQL 数据库中设置值
- python - Tensorflow,tf.where的参数
- python - 将列表中的元素添加到字典并增加值
- ios - 在 UIGraphicsBeginImageContextWithOptions 中绘制图像时出现 ECC_BAD_ACCESS
- vba - 重新排列列并将范围导出到 CSV
- angular - Angular 5 http客户端,订阅时执行功能
- php - 基于下拉选择Laravel 5.6过滤数据
- kubernetes - vert.x 事件总线消息的 Istio 请求跟踪
- html - 倾斜 div 容器上的文本溢出