如何将prevState反向保存三次?



因为CSStransitions使组件渲染三次,所以我需要将prevState向后存储三次。

有什么好主意吗?我应该用useEffectuseRef吗?

这里有一个例子,这样会更清楚:

const [count, setCount] = useState(0);
<button onClick={() => setCount(count + 1)}>+</button>

const 3statesBackwards = 0;
// so when count gets to 3, 3statesBackwards is 0,
// if count get to 8, 3statesBackwards will be 5.

为什么不使用新的useState属性来保存这些值呢?

const [prevCount, setPrevCount] = useState({lastCurrent: 0,prev1: 0, prev2: 0, prev3: 0});
useEffect( () => {
setPrevCount( prev => ({
lastCurrent: count,
prev1: prev.lastCurrent,
prev2: prev.prev1,
prev3: prev.prev2
})
}, [count]);

最新更新