简体   繁体   中英

React hooks get previous state of state A when setting state of state B

For example, if I have two pieces of state:

const [a, setA] = useState(0);
const [b, setB] = useState(0);

And I want to update b using the previous state of both a and b, is there a way to do it without grouping them in an object?

It seems that you can only update the state using the previous state of the same piece of state, like so:

setB(b => b + 1)

you can use hook useCallback and add in dependencies variable a

const setVariable = useCallback(() => {
    setB(b => b + a)
}, [a]);

最近才意识到这里最好的解决方案是使用useReducer钩子。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM