[英]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?我想使用 a 和 b 的先前状态更新 b,有没有办法在不将它们分组到一个对象中的情况下做到这一点?
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您可以使用钩子useCallback并添加依赖项变量a
const setVariable = useCallback(() => {
setB(b => b + a)
}, [a]);
最近才意识到这里最好的解决方案是使用useReducer
钩子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.