Ash*_*mar 3 setinterval clearinterval reactjs react-hooks use-ref
我试图理解 React 中的 useRef 钩子。
我在 React 中创建了一个简单的时间。其代码如下。
import { useRef, useState, useEffect } from 'react';
function Parent() {
const [count,setCount]=useState(5);
const ref=useRef(0);
//let hold=0;
const countdown=()=>{
ref.current=setInterval(()=>{
// console.log('ref.current-->',ref.current);
setCount((c)=>c-1)
},1000)
}
useEffect(()=>{
if(count<1)
clearInterval(ref.current)
},[count])
return(
<>
<h3>Timer : {count}</h3>
<br/>
<button onClick={countdown}>countdown</button>
</>
)
}
export default Parent;
Run Code Online (Sandbox Code Playgroud)
在这里,我使用钩子创建了一个引用,并且正在监视计数状态。当它达到 0 时,我将调用“clearInteval”函数来清除计时器。
这段代码工作正常。
但是,当我尝试使用普通变量而不是由挂钩创建的变量执行相同操作时,间隔不会被清除。
请在下面找到相同的代码。
import { useRef, useState, useEffect } from 'react';
function Parent() {
const [count,setCount]=useState(5);
const ref=useRef(0);
let hold=0;
const countdown=()=>{
hold=setInterval(()=>{
// console.log('ref.current-->',ref.current);
setCount((c)=>c-1)
},1000)
}
useEffect(()=>{
if(count<1)
clearInterval(hold)
},[count])
return(
<>
<h3>Timer : {count}</h3>
<br/>
<button onClick={countdown}>countdown</button>
</>
)
}
export default Parent;
Run Code Online (Sandbox Code Playgroud)
我在这里不明白什么?
这段代码应该可以在正常的 JavaScript 中运行。
const myRef = useRef()将提供一个 ref 对象,使得myRef.current的值将在渲染过程中保持不变。当您使用 时let myVar = something,myVar将在每次渲染时重新创建,因此您每次都会丢失并替换它的值。
每次状态发生变化时,您的Parent组件都会重新渲染,因此您可以通过将间隔引用保留为来自 的引用而受益useRef。
| 归档时间: |
|
| 查看次数: |
2572 次 |
| 最近记录: |