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

IT技术 reactjs redux
2021-05-06 09:57:42

在减速器中的这种上下文中更新状态的更好方法是什么?

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 - case 块中的意外词法声明

2个回答

ESLint 不喜欢 reducer 中 case 块内的 let 语句,为什么?

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

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

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

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

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

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