有条件重新分配的 ESLint prefer-const 错误
ESLint prefer-const error with conditional reassign
是否有一种特殊的方法可以在条件语句中重新分配 let
以避免不断出现 prefer-const
eslint
错误?
我的代码:
let jsx = [];
if (a === b) {
jsx.push(
<div>
xxx
</div>
);
}
jsx.push(<div>yyy</div>);
===更新===
不好意思打扰了,其实这不是重新赋值操作。
您可以使用 const
因为您没有重新分配 jsx
变量,只是推入它指向的数组:
const jsx = [];
if (a === b) {
jsx.push(
<div>
xxx
</div>
);
}
jsx.push(<div>yyy</div>);
您没有重新分配 jsx
变量,您只是在修改它。使用 const
声明的变量可以被修改,因此您可以将 let
替换为 const
.
来自MDN:
The const
declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in case the content is an object, this means the object itself can still be altered.
示例:
const arr = [];
arr.push(42);
console.log(arr);
是否有一种特殊的方法可以在条件语句中重新分配 let
以避免不断出现 prefer-const
eslint
错误?
我的代码:
let jsx = [];
if (a === b) {
jsx.push(
<div>
xxx
</div>
);
}
jsx.push(<div>yyy</div>);
===更新=== 不好意思打扰了,其实这不是重新赋值操作。
您可以使用 const
因为您没有重新分配 jsx
变量,只是推入它指向的数组:
const jsx = [];
if (a === b) {
jsx.push(
<div>
xxx
</div>
);
}
jsx.push(<div>yyy</div>);
您没有重新分配 jsx
变量,您只是在修改它。使用 const
声明的变量可以被修改,因此您可以将 let
替换为 const
.
来自MDN:
The
const
declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in case the content is an object, this means the object itself can still be altered.
示例:
const arr = [];
arr.push(42);
console.log(arr);