如何在 React Hooks 上获取先前的变量值

How to get previous variable value on React Hooks

我有一个已经根据 API 结果设置的变量,值是一个数组:

tier_items = [{id:1, name:'coffee'}, {id:2, name:'tea'}, {id:2, name:'juice'}]

tier_items 值始终根据此条件更新

useEffect(()=>{console.log('tier_items')}, [tier_items])

更新后的值:tier_items = [{id:1, name:'coffee'}]

我需要获取更新后的先前值和当前值 tier_items

const [current, setCurrent] = useState(tier_items) 
const [previous, setPrevious] = ???

这是预期的结果

current = [{id:1, name:'coffee'}]

previous = [{id:1, name:'coffee'}, {id:2, name:'tea'}, {id:2, name:'juice'}]

还有下一个值

更新当前时必须更新以前的,例如:

setCurrent((current) => {
    setPrevious((currentPrevious) => return [...current, ...currentPrevious])
    return [{id:1, name:'coffee'}];
}

那应该做你想要的:)