反应设置状态不能立即工作
react set state isn't working immediately
我正在制作一个基于函数的 React 组件,需要使用按钮设置状态,但很快意识到 setstate 工作不佳,这是我使用的代码:
function Test() {
const [index, setindex] = useState(0)
function next() {
console.log(index);
setindex(1)
console.log(index);
}
function pre() {
console.log(index);
setindex(-1)
console.log(index);
}
return (
<div>
<button onClick={next}>next</button>
<button onClick={pre}>previous</button>
</div>
)
}
console显示index设置前后是一样的,也是设置了一键延时。我知道我可以使用单选按钮来做到这一点,因为它们出于某种原因工作正常,但它似乎是一个糟糕的解决方案。你能告诉我为什么它会那样吗
useState 本质上是异步的。如果不会像您期望的那样立即反映出来。
如果您在状态更改后需要任何东西,请使用 useEffect
,例如:
useEffect(() => {
if(index === 'blah') { // your value here
console.log(index)
}
}, [index]);
或者您可以像这样使用回调:
setState(prevState => {
// Object.assign would also work
return {...prevState, ...updatedValues};
});
我正在制作一个基于函数的 React 组件,需要使用按钮设置状态,但很快意识到 setstate 工作不佳,这是我使用的代码:
function Test() {
const [index, setindex] = useState(0)
function next() {
console.log(index);
setindex(1)
console.log(index);
}
function pre() {
console.log(index);
setindex(-1)
console.log(index);
}
return (
<div>
<button onClick={next}>next</button>
<button onClick={pre}>previous</button>
</div>
)
}
console显示index设置前后是一样的,也是设置了一键延时。我知道我可以使用单选按钮来做到这一点,因为它们出于某种原因工作正常,但它似乎是一个糟糕的解决方案。你能告诉我为什么它会那样吗
useState 本质上是异步的。如果不会像您期望的那样立即反映出来。
如果您在状态更改后需要任何东西,请使用 useEffect
,例如:
useEffect(() => {
if(index === 'blah') { // your value here
console.log(index)
}
}, [index]);
或者您可以像这样使用回调:
setState(prevState => {
// Object.assign would also work
return {...prevState, ...updatedValues};
});