[英]Why am I getting a 'no-unused-var' error when using in an inline function
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. 您在函数中使用的
prevState
被声明为函数的参数。 It is shadowing the const
-declared prevState
from the outer scope. 它从外部作用域中隐藏了
const
声明的prevState
。
What's the best way to make the error go away?
使错误消失的最佳方法是什么?
Assuming the function is working as is, just omit the const
declaration. 假设函数按原样工作,则省略
const
声明。
Try this (ie remove the line where you declare prevState
): 尝试以下操作(即删除声明
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. Eslint抱怨说,此后您已经声明了常量
prevState
却从未使用过。 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. 该
prevState
你里面setState
调用是正确的-第一个参数setState
发送到你的回调函数是以前的状态,这就是你想要的回调函数内使用的。
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 您实际上没有使用您声明的prevState
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.