usePrevious作用:保存上一次状态的 Hook。
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
}
使用:
const [counter, setCounter] = useState(0);
const previous = usePrevious(counter);
const handleClick = () => {
setCounter((state) => state + 1);
};
return (
<div>
<div>{`counter:${counter} `} </div>
<div>{`previous:${previous} `} </div>
<div onClick={handleClick}>点我啊 dd </div>
</div>
);