reactjs - useRef 如何用于存储先前的状态
问题描述
function Counter() {
const [count, setCount] = useState(0);
const prevCountRef = useRef();
useEffect(() => {
prevCountRef.current = count; });
const prevCount = prevCountRef.current;
return <h1>Now: {count}, before: {prevCount}</h1>;
}
在上面的代码片段中,React Hoks FAQS
useRef
用于保存计数。但是,每当调用 render 时,不会prevCount
将 设置为当前count
,因为useEffect
将在每次渲染时调用,那么 count 和 prevCount 有何不同?
解决方案
这是因为useEffect
回调函数会在 Component 完成后被rendering time
调用Counter
。这就是为什么prevCount
总是tick
落后。
需要考虑的一点是,a 中的更改React ref
不会导致 React 组件中的重新渲染,只会change in state and props
导致重新渲染。
在此处查看工作示例:https ://codesandbox.io/s/lucid-butterfly-y66tc?file=/src/App.js
export default function Counter() {
const [count, setCount] = useState(0);
const prevCountRef = useRef();
useEffect(() => {
prevCountRef.current = count;
console.log('me socond')
});
console.log('me first')
const prevCount = prevCountRef.current;
return (
<h1>
Now: {count}, before: {prevCount}
<div onClick={() => setCount((v) => v + 1)}>click me</div>
</h1>
);
}
me first
然后me second
在控制台中看到
推荐阅读
- php - 设置 WooCommerce 计费公司时禁用特定付款方式
- python - 如何更正此错误:OverflowError: cannot convert float infinity to integer
- c# - 在 C# 方法中将 PowerShell 参数从字典更改为字符串列表
- python - plotly dash chart:无法访问网站
- javascript - Javascript / jQuery onClick 将带有图像的句子发送到输入表单
- c++ - Visual Studio 2019:传递包含链引用项目之间的路径
- javascript - 在 onClick 属性中枚举存储在 state 中的函数数组
- angular - 在 Angular 中测试 AsyncValidators - 测试通过但不确定期望语句正在运行/执行
- php - 使用 PHP 在 GCS 上合并 CSV 文件
- batch-file - 如何获取公共 ipv4 而不是 ipv6