Reactjs 如何以功能性的方式使用挂钩更新react组件
我想做一个简单的时钟,每秒钟更新一次我真的是新的反应,所以我有点困惑如何使用函数中的挂钩我现在正在尝试这一点,困在如何更新setTimer和显示更新返回函数 提前谢谢Reactjs 如何以功能性的方式使用挂钩更新react组件,reactjs,Reactjs,我想做一个简单的时钟,每秒钟更新一次我真的是新的反应,所以我有点困惑如何使用函数中的挂钩我现在正在尝试这一点,困在如何更新setTimer和显示更新返回函数 提前谢谢 import React, { useState } from 'react'; function Timer() { const [timer, setTimer] = (useState(new Date().toLocaleTimeString())); return ( <div
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
import React,{useState}来自“React”;
函数计时器(){
const[timer,setTimer]=(useState(new Date().toLocaleTimeString());
返回(
它是{timer}。
)
}
导出默认计时器
您可以使用钩子
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
你可以用钩子
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
()=>clearinterval(interval)它在赋值或函数调用时给出了预期的错误,但看到了一个表达式。eslint(无未使用的表达式)“clearinterval”未定义。eslint(无未定义)@Avinash,它是
clearinterval
(大写I
)检查更新的答案。仍然在同一行函数clearInterval(intervalId:NodeJS.Timeout):void(+1重载)预期一个赋值或函数调用,但看到了一个表达式。eslint(没有未使用的表达式)useffect(()=>{const interval=setInterval(()=>{setTimer(new Date().toLocaleTimeString())},1000);()=>clearInterval(interval)},[timer])@Avinash,这是我的错,忘了添加返回。检查更新的答案。(=>clearinterval(interval)它给出了一个预期的错误赋值或函数调用,而看到了一个表达式。eslint(没有未使用的表达式)“clearinterval”没有定义。eslint(没有未定义)@Avinash,它是clearinterval
(大写I
)检查更新的答案。仍然在同一行函数clearInterval(intervalId:NodeJS.Timeout):void(+1重载)预期一个赋值或函数调用,但看到了一个表达式。eslint(没有未使用的表达式)useffect(()=>{const interval=setInterval(()=>{setTimer(new Date().toLocaleTimeString())},1000);()=>clearInterval(interval)},[timer])@Avinash,这是我的错,忘了添加返回。检查更新的答案。