import React, { useState, useRef } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const prevCountRef = useRef();
// 保存上一次的值
prevCountRef.current = count;
const handleClick = () => {
console.log('改变前的值:', prevCountRef.current);
setCount(count + 1);
};
return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>增加</button>
</div>
);
}
react如何保留上一次的值
最新推荐文章于 2024-06-17 16:46:34 发布