在功能性反应组件中,我在相同的渲染周期内发生了多个状态更新:
function Counter() {
const [count, setCount] = React.useState(0);
const [flag, setFlag] = React.useState(false);
function handleClick() {
setCount((prev) => prev + 1);
setCount((prev) => prev + 1);
setFlag((prev) => !prev);
}
console.log("Render:", { count, flag });
return <button onClick={handleClick}>Increment</button>;
}
我的问题:
const [one,setOne] = useState(0)
useState
如果您的要求在一个功能中具有多个状态更新,并且您对先前更新有依赖性,那么您需要使用
setOne((prev) => prev+1) // This will promise after this operation your function will go to next line
所以现在您的输出变为
setOne((prev) => prev+1) // Now one becomes 1
setOne((prev) => prev+1) // Now one becomes 2
console.log(one) // now you will `2` get what you want
但是,当您对以前没有任何依赖性时,您可以像这样使用
setOne(one+1)
但是您仍然有依赖性,然后像这样写了这样的人setOne(one+1) // it is still updating one = 0
setOne(one+1) // you updated but above line still not executed and one = 0
console.log(one) // Now you will get `1` as answer
等待什么?您更新了两次,所以答案是
2
对吗?
不,不是真的,当那时第二次指令执行时,第一个指令仍在运行,但第二行也执行并返回。