简体   繁体   English

防止在 this.setState 中使用 this.state (react/no-access-state-in-setstate)

[英]Prevent using this.state within a this.setState (react/no-access-state-in-setstate)

For this piece of code, !this.state.dark I am getting an ESlint (airbnb config) error:对于这段代码, !this.state.dark我收到了一个 ESlint (airbnb config) 错误:

Use callback in setState when referencing the previous state.

I tried refactoring the code using following the ESlint documentation .我尝试使用以下ESlint 文档重构代码。 But I'm having a hard time figuring it out.但我很难弄清楚。 Any suggestions on how I can solve this problem?关于如何解决这个问题的任何建议?

toggleDark = () => {
  const dark = !this.state.dark
  localStorage.setItem('dark', JSON.stringify(dark))
  this.setState({ dark })
}

Thanks to @jonrsharpe for pointing me to appropriate documentation.感谢@jonrsharpe 为我指出适当的文档。

It turns out that state updates may be asynchronous.事实证明,状态更新可能是异步的。 React may batch multiple setState() calls into a single update for performance. React 可以将多个 setState() 调用批处理为单个更新以提高性能。 In the came of my code, I only have one value that was being updated.在我的代码中,我只有一个正在更新的值。 But, it's still a good idea to use a second form of setState that accepts a function rather then an object.但是,使用接受函数而不是对象的第二种形式的 setState 仍然是一个好主意。

toggleDark = () => {
  const dark = !this.state.dark
  localStorage.setItem('dark', JSON.stringify(dark))

  this.setState(({ dark }) => ({ dark: !dark }))
}
toggleDark = () => {
  const dark = !this.state.dark
  localStorage.setItem('dark', JSON.stringify(dark))
  this.setState({...this.state, dark: !dark })
}

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

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