因为CSStransitions
使组件渲染三次,所以我需要将prevState
向后存储三次。
有什么好主意吗?我应该用useEffect
和useRef
吗?
这里有一个例子,这样会更清楚:
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]);