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

∥☆過路亽.° 提交于 2020-01-06 05:05:27

问题


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 })
}

回答1:


Thanks to @jonrsharpe for pointing me to appropriate documentation.

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 }))
}


来源:https://stackoverflow.com/questions/59005886/prevent-using-this-state-within-a-this-setstate-react-no-access-state-in-setsta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!