Here's a snippent of my code:
const prevState = this.state;
this.setState(prevState => ({
companies_checked: {
...prevState.companies_checked,
[target.value]: target.checked
}
}));
It is generating the following error:
Line 52: 'prevState' is assigned a value but
never used no-unused-vars
I'm using the variable in the inline/arrow function. What's the best way to make the error go away?
I'm using the variable in the inline/arrow function.
No, you don't. The prevState
that you use in the function is declared as the function's parameter. It is shadowing the const
-declared prevState
from the outer scope.
What's the best way to make the error go away?
Assuming the function is working as is, just omit the const
declaration.
Try this (ie remove the line where you declare prevState
):
this.setState(prevState => ({
companies_checked: {
...prevState.companies_checked,
[target.value]: target.checked
}
}));
Eslint is complaining that you have declared the constant prevState
without ever using it, afterwards. The correct way to fix the problem is to simply not declare it in the first place.
The prevState
inside your setState
call is correct - the first argument setState
sends to your callback function is the previous state, and this is the one you want to use inside the callback function.
I think it is just naming conflict.
// you already declared prevState
const prevState = this.state;
// change to this.setState(previousState =>
this.setState(prevState => ({
companies_checked: {
...prevState.companies_checked,
[target.value]: target.checked
}
}));
You actually did not use prevState that you declared
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.