反应设置状态不能立即工作

时间:2021-02-09 10:26:00

标签: reactjs react-state

我正在制作一个基于函数的 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>
    )
}

控制台显示索引在设置之前和之后是相同的,并且它也设置了一个按钮按下的延迟。我知道我可以使用单选按钮来做到这一点,因为出于某种原因它们可以正常工作,但这似乎是一个糟糕的解决方案。你能告诉我为什么它会这样

1 个答案:

答案 0 :(得分:0)

useState 本质上是异步的。如果不会像您期望的那样立即反映。

如果在更改状态后需要任何内容​​,请使用 useEffect 如下:

useEffect(() => {
   if(index === 'blah') { // your value here 
     console.log(index)
   }
}, [index]);

或者你可以像这样使用回调:

setState(prevState => {
  // Object.assign would also work
  return {...prevState, ...updatedValues};
});
相关问题