【问题标题】:eslint: no-case-declaration - unexpected lexical declaration in case blockeslint: no-case-declaration - case 块中的意外词法声明
【发布时间】:2018-11-18 01:30:42
【问题描述】:

在这个上下文中,在 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: no-case-declaration - 意外的词法声明以防万一 阻止

【问题讨论】:

  • deleteInterests 仍然是对状态数组的引用,因此您仍在变异。拼接前先克隆列表。
  • {} 用于switch 中的case DELETE_INTEREST 以根据eslint.org/docs/rules/no-case-declarations 消除此棉绒问题

标签: reactjs redux


【解决方案1】:

ESLint 不喜欢在 a 中的 case 块中使用 let 语句 减速机,为什么?

不鼓励这样做,因为它会导致变量在当前case 之外的范围内。通过使用块,您可以将变量的范围限制在该块内。

使用{} 创建带大小写的块作用域,如下所示:

case DELETE_INTEREST: {
    let .....
    return (...)
}

检查这个sn-p:

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 将在原始数组中进行更改。像这样写:

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

【讨论】:

  • 为什么? :)
  • 据我了解,如果您在 case 块内声明一个变量而不使用 {} 限定它,您的变量将在 switch 块中可用,但只会在这种情况下分配块(如果不通过这种情况,有可能不会被宣布)eslint.org/docs/rules/no-case-declarations
【解决方案2】:

尝试用 {} 封装外壳内部 像这样看起来很简单的例子

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 2015-08-02
    • 1970-01-01
    相关资源
    最近更新 更多