简体   繁体   English

使用 React Hooks 根据之前的状态更改状态

[英]Change the state based on the previous state with React Hooks

I was watching a tutorial and in one moment he does this:我正在看一个教程,有一次他这样做了:

export default function Editor(props) {
  const [open, setOpen] = useState(true);

  return (
    <div className={`container ${open ? "" : "collapsed"}`}>
       <button onClick={() => setOpen((prevOpen) => !prevOpen)}>O/C</button>
    </div>
  );
}

My question is: why this我的问题是:为什么这

<button onClick={() => setOpen((prevOpen) => !prevOpen)}>O/C</button>

and not并不是

<button onClick={() => setOpen(!open)}>O/C</button>

I tried both and they seem to work.我尝试了两者,它们似乎有效。

Because open may not actually be the previous state.因为open可能实际上不是以前的状态。 In your code it is, but in more complicated components there may be multiple pieces of code that set state.在您的代码中是这样,但在更复杂的组件中,可能会有多段代码设置状态。 If these happen at around the same time, react may batch them up and apply them all at once.如果这些几乎同时发生,react 可能会将它们分批并一次性全部应用。

Usually, these pieces of code will be in separate parts of the component and thus it's hard to spot.通常,这些代码片段位于组件的不同部分,因此很难被发现。 But for demonstration purposes, i'll put them right next to eachother:但出于演示目的,我会将它们放在一起:

onClick={() => {
  setOpen(!open)
  setOpen(!open)
})

With the above code, we ask react to set the state to false , and then we ask react to set the state to false again.使用上面的代码,我们要求 react 将状态设置为false ,然后我们要求 react 再次将状态设置为false End result is that it's false.最终的结果是它是假的。 That's probably not what's intended: if we toggle the state twice, it's probably because we want it to go back to the original state.这可能不是我们想要的:如果我们两次切换状态,可能是因为我们希望它回到原始状态。

onClick={() => {
  setOpen((prevOpen) => !prevOpen)
  setOpen((prevOpen) => !prevOpen)
})

This code will set it to false , and then set it to true .此代码将其设置为false ,然后将其设置为true Each function gets passed in the most recent value, even if that value is different than the value of open in the closure.每个函数都会传入最新的值,即使该值与闭包中的open值不同。

When you want to update the state which depends on the previous state then you need to call the setState like <button onClick={() => setOpen((prevOpen) => !prevOpen)}>O/C</button> .当你想更新依赖于前一个状态的状态时,你需要像<button onClick={() => setOpen((prevOpen) => !prevOpen)}>O/C</button>一样调用 setState 。 This is the important rule of how you set the state.这是设置状态的重要规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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