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

nfs0ujit  于 2022-11-24  发布在  其他
关注(0)|答案(3)|浏览(171)

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

mzillmmw

mzillmmw1#

ESLint不喜欢在reducer中的case块中使用let语句,为什么?
不建议这样做,因为这会导致变量位于当前case的作用域之外。通过使用块,可以将变量的作用域限制在该块内。
使用{}创建带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 } };
kt06eoxx

kt06eoxx2#

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

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

prdp8dxp3#

一个简单的解决方法是使用括号{}来封装case代码。如果使用return,在某些情况下可能需要添加break

相关问题