eslint: no-case-declaration - case 块中意外的词法声明 [英] eslint: no-case-declaration - unexpected lexical declaration in case block
问题描述
在reducer 中的这种上下文中更新状态的更好方法是什么?
What is the better way to update state in this context inside a reducer?
case DELETE_INTEREST:
let deleteInterests = state.user.interests;
let index = deleteInterests.findIndex(i => i == action.payload);
deleteInterests.splice(index, 1);
return { ...state, user: { ...state.user, interests: deleteInterests } };
ESLint 不喜欢 reducer 中 case 块内的 let 语句,得到:
ESLint doesn't like let statements inside case blocks inside a reducer, getting:
eslint: no-case-declaration - 意外的词法声明以防万一块
eslint: no-case-declaration - unexpected lexical declaration in case block
推荐答案
ESLint 不喜欢在 case 块内的 let 语句减速机,为什么?
ESLint doesn't like let statements inside case blocks inside a reducer, Why?
不鼓励这样做,因为它会导致变量在当前case
之外的范围内.通过使用块,您可以将变量的范围限制为该块.
This is discouraged because it results in the variable being in scope outside of your current case
. By using a block you limit the scope of the variable to that block.
使用 {}
创建带大小写的块作用域,如下所示:
Use {}
to create the block scope with case, like this:
case DELETE_INTEREST: {
let .....
return (...)
}
检查这个片段:
function withOutBraces() {
switch(1){
case 1:
let a=10;
console.log('case 1', a);
case 2:
console.log('case 2', a)
}
}
function withBraces() {
switch(1){
case 1: {
let a=10;
console.log('case 1', a);
}
case 2: {
console.log('case 2', a)
}
}
}
console.log('========First Case ============')
withOutBraces()
console.log('========Second Case ============')
withBraces();
要从数组中删除元素,请使用 array.filter,因为 splice 将对原始数组进行更改.像这样写:
For deleting the element from array, use array.filter, because splice will do the changes in original array. Write it like this:
case DELETE_INTEREST:
let deleteInterests = state.user.interests;
let newData = deleteInterests.filter(i => i !== action.payload);
return { ...state, user: { ...state.user, interests: newData } };
这篇关于eslint: no-case-declaration - case 块中意外的词法声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!