我已阅读了《使用效果的完全指南-过度反应应对潮流》。
该示例表明,如果我们想获取最新的count,我们可以useRef用来保存可变变量,并在异步函数laster中获取它:
function Example() {
const [count, setCount] = useState(0);
const latestCount = useRef(count);
useEffect(() => {
// Set the mutable latest value
latestCount.current = count;
setTimeout(() => {
// Read the mutable latest value
console.log(`You clicked ${latestCount.current} times`);
}, 3000);
});
// ...
}
Run Code Online (Sandbox Code Playgroud)
但是,我可以通过在组件函数外部创建一个变量来执行相同的操作,例如:
import React, { useState, useEffect, useRef } from 'react';
// defined a variable outside function component
let countCache = 0;
function Counter() {
const [count, setCount] = useState(0); …Run Code Online (Sandbox Code Playgroud)