eslint: no-case-declaration - unexpected lexical declaration in case block

前端 未结 1 1012
借酒劲吻你
借酒劲吻你 2021-02-04 23:01

What is the better way to update state in this context inside a reducer?

case DELETE_INTEREST:
    let deleteInterests = state.user.interests;
    let index = de         


        
相关标签:
1条回答
  • 2021-02-04 23:35

    ESLint doesn't like let statements inside case blocks inside a reducer, Why?

    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 (...)
    }
    

    Check this snippet:

    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();

    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 } };
    
    0 讨论(0)
提交回复
热议问题