- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
如何在每个“useEffect”中使用变量的更新值(在组件范围内声明)?
import React, { useState, useEffect } from 'react';
export default function Count() {
const [count, setCount] = useState(0);
let a = 10;
useEffect(() => {
console.log('after 1st render', a);
a++;
console.log(a);
return () => { console.log('cleanup - on unmount.') }
}, [a]);
useEffect(() => {
console.log('only when count changes', a);
a++;
return () => { console.log('count cleanup', a) }
}, [count, a]);
return <div>
<p>Count : {count}</p>
<button onClick={() => { console.log('at global', a); setCount(count + 1) }}>Click</button>
</div>
}
output
after 1st render 10
11
only when count changes 11
at global 12
count cleanup 12
only when count changes 10
现在,我从这个输出中不明白的是最后一行将“a”的值输出为 10。
每次调用 useEffect 时,它都会创建所提供函数的新副本,并且还会调用 cleanUp 函数,对吗?
当我点击按钮时,计数发生变化,之前的 cleanUp 被调用并清除将 'a' 的值从 11 设置为 12 的 'useEffect' 行为,然后使用值为 10 调用当前的 'useEffect'。它应该打印值 11。 ?谁能澄清一下。
最佳答案
在每次渲染时,执行所有 Count
主体,因此通过单击按钮更改状态将导致调用 let a = 10
并重置 a
.
换句话说,局部变量a
的生命周期是直到下一次渲染。
要获得所需的行为,请尝试使用 useRef
的引用.
useRef returns a mutable ref object whose .current property isinitialized to the passed argument (initialValue). The returned objectwill persist for the full lifetime of the component.
const [count, setCount] = useState(0);
const aRef = useRef(10);
let a = 10;
useEffect(() => {
console.log("after 1st render", a);
a++;
aRef.current++;
console.log(a);
return () => {
console.log("cleanup - on unmount.");
};
}, [a]);
useEffect(() => {
console.log("only when count changes", a);
console.log("only when count changes - ref", aRef.current);
a++;
aRef.current++;
return () => {
console.log("count cleanup", a);
};
}, [count, a]);
结果:
only when count changes10
only when count changes - ref12
阅读更多信息 uses of useEffect
关于javascript - 如何在 'useEffect' 钩子(Hook)中获取最新的组件变量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57240777/
我是一名优秀的程序员,十分优秀!