我有一个如下所示的函数,其中 isformValid 被标记为 let 并在 if block 中使用它并根据条件更改其值。
validateForm(validationErrors, formData) {
let validationRules = this.state.dynamicJourneyData[this.state.currentStepName].validationRules;
let isFormValid = true;
let fullErrorList = [];
validationRules.rules.forEach((rule) => {
let errorList = this.evaluateRule(rule, formData);
if (errorList.length > 0) {
fullErrorList = fullErrorList.concat(errorList);
}
});
let finalErrorList = [];
let errorKeys = [];
fullErrorList.filter((error) => errorKeys.indexOf(error.id) < 0).forEach((error) => {
finalErrorList.push(error);
errorKeys.push(error.id);
});
if (finalErrorList.length > 0) {
isFormValid = false;
if (finalErrorList.length === 1) {
validationErrors.messageTitle = validationErrors.messageTitle
.replace('@count', finalErrorList.length)
.replace('were', 'was')
.replace('errors', 'error');
} else {
validationErrors.messageTitle = validationErrors.messageTitle.replace('@count', finalErrorList.length);
}
validationErrors.messageBody = finalErrorList; /*(fullErrorList.map(error=>error.label)).toString();*/
}
return finalErrorList;
}
我可以看到一个 eslint 错误,因为“isFormValid”被分配了一个值但从未使用过,尽管我在 if block 中使用了它。
最佳答案
ESLint 文档对此进行了很好的描述(https://eslint.org/docs/rules/no-unused-vars):
// Write-only variables are not considered as used.
var y = 10;
y = 5;
您向 isFormValid
写入了两次(在初始化期间和 if block 中),但存储在变量中的值从未被读取,因此触发了 linting 错误。当函数返回时,存储在局部变量中的值将被丢弃。由于该值从未被读取或返回,因此它不会改变计算结果的任何内容。看起来您的代码中根本不需要这个变量。
关于javascript - es lint '' 被分配了一个值但从未使用过'尽管我已经使用过它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53129557/