javascript - React:usePrevious 钩子仅在组件中有 1 个状态时才有效。如果有多个状态,如何使其工作?
问题描述
文档建议以下获取先前状态:
function Counter() {
const [count, setCount] = useState(0);
const prevCount = usePrevious(count);
return <h1>Now: {count}, before: {prevCount}</h1>;
}
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
根据我的理解,只有在组件中只有一个状态时才能正常工作。但是,如果有多个状态,请考虑以下情况:
import "./styles.css";
import React, { useState, useEffect, useRef, useContext } from "react";
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
export default function App() {
const [count, setCount] = useState(0);
const [foo, setFoo] = useState(0);
const prevCount = usePrevious(count);
return (
<div>
<button onClick={() => setFoo(f => f+1)}> Update foo </button>
<h1>Now: {count}, before: {prevCount}</h1>
</div>);
}
沙盒:https ://codesandbox.io/s/little-feather-wow4m
当一个不同的foo
状态(
当有多个状态时,有没有办法可靠地获取状态/道具的先前值?
解决方案
我不认为这是正确的做法。
如何设置状态并返回为您处理此逻辑的自定义设置器函数的自定义钩子。
function useStateWithPrevious(initial) {
const [value, setValue] = useState(initial)
const [prev, setPrev] = useState(initial)
function setValueAndPrev(newValue) {
if (newValue === value) return // optional, depends on the logic you want.
setPrev(value)
setValue(newValue)
}
return [prev, value, setValueAndPrev]
}
您会使用如下:
function MyComponent() {
const [prevCount, count, setCount] = useStateWithPrevious(0)
}
推荐阅读
- python - 尝试自动化键盘快捷键,尝试过 Pyautogui 和键盘
- geolocation - 如何在反应原生博览会中使用纬度和经度计算两点之间的距离?
- python - 如何在 Python 中与字符串进行交叉乘法?
- python - Python:如何访问生成器对象中的元素并将它们放入 Pandas 数据框或字典中?
- android - 为什么 ViewModel 中的协程方法离开 Fragment 后还在继续处理?
- asp.net-core - 全局异常hadling .net核心不起作用
- angular - 如何从传单地理编码器在谷歌地图中添加标记
- python-3.x - 手动实现近似函数
- javascript - 空手道模糊匹配 - 构建自定义标记
- javascript - 使用像 eval 这样的字符串模板