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

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

对于这段代码,!this.state.dark我遇到了 ESlint(airbnb 配置)错误:

Use callback in setState when referencing the previous state.

我尝试使用 ESlint documentation 重构代码。但我很难弄清楚。关于如何解决这个问题有什么建议吗?

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

感谢@jonrsharpe 为我指点适当的文档。

事实证明,状态更新可能是异步的。 React 可以将多个 setState() 调用批处理到单个更新中以提高性能。在我的代码中,我只有一个正在更新的值。但是,使用接受函数而不是对象的第二种形式的 setState 仍然是个好主意。

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

  this.setState(({ dark }) => ({ dark: !dark }))
}