eslint:no-case-declaration - case块中的意外词法声明

Jos*_*osh 24 reactjs redux

在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 } };
Run Code Online (Sandbox Code Playgroud)

ESLint不喜欢在reducer中的case块内部使用let语句,得到:

eslint:no-case-declaration - case块中的意外词法声明

May*_*kla 63

ESLint不喜欢let语句块里面的let语句,为什么?

使用{}来创建情况下,块范围,就像这样:

case DELETE_INTEREST: {
    let .....
    return (...)
}
Run Code Online (Sandbox Code Playgroud)

检查此代码段:

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();
Run Code Online (Sandbox Code Playgroud)

要从数组中删除元素,请使用array.filter,因为splice将对原始数组进行更改.写这样:

case DELETE_INTEREST:
    let deleteInterests = state.user.interests;
    let newData = deleteInterests.filter(i => i !== action.payload);
    return { ...state, user: { ...state.user, interests: newData } };
Run Code Online (Sandbox Code Playgroud)

  • 据我了解,如果您在“case”块内声明一个变量,而没有使用“{}”对其进行范围限定,则该变量将在 switch 块中可用,但只会在该 case 块中分配(存在不会被分配的风险)如果没有经历这种情况则被声明)https://eslint.org/docs/rules/no-case-declarations (6认同)
  • 但为什么呢?:) (5认同)

小智 27

尝试用 {} 封装内部,就像这个看起来简单的例子

      case EnumCartAction.DELETE_ITEM: {
           const filterItems = state.cart.filter((item) => item._id !== action.payload)
           return {
                ...state,
                cart: filterItems
           }
      }
Run Code Online (Sandbox Code Playgroud)