问题
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