禁止在this.setState中使用this.state(反应/无访问状态-设置状态) [英] Prevent using this.state within a this.setState (react/no-access-state-in-setstate)

查看:1159
本文介绍了禁止在this.setState中使用this.state(反应/无访问状态-设置状态)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For this piece of code, !this.state.dark I am getting an ESlint (airbnb config) error:

Use callback in setState when referencing the previous state.

我尝试使用

I tried refactoring the code using following the ESlint documentation. 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 })
}

推荐答案

感谢@jonrsharpe向我指出了适当的文档.

Thanks to @jonrsharpe for pointing me to appropriate documentation.

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

It turns out that state updates may be asynchronous. React may batch multiple setState() calls into a single update for performance. 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.

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

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

这篇关于禁止在this.setState中使用this.state(反应/无访问状态-设置状态)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆