Is this redux reducer OK

时间:2019-04-08 13:59:14

标签: javascript reactjs redux immutability

Is this reducer OK:

function someReducer(state = initialState, action) {
   if (action.type === SOME_ACTION) {
      const newState = Object.assign( {}, state );
      // ...
      // doing whatever I want with newState 
      // ...
      return newState;
   }   
   return state;
}

and if is OK, why we need all those immutable libraries to complicate our lives.

p.s Just trying to comprehend Redux and immutability

4 个答案:

答案 0 :(得分:5)

export default function (state = initialState, action) {

  const actions = {
    SOME_ACTION: () => {
      return {
        ...state
      }
    },
    ANOTHER_ACTION: () => {
      return {
        ...state
        error: action.error
      }
    }
    DEFAULT: () => state;
  }
  
  return actions[action.type] ? actions[action.type]() : actions.DEFAULT(); 
}

我宁愿这样做。我不喜欢switch语句。

答案 1 :(得分:3)

The standard approach is to use a switch/case with spread syntax (...) in your reducer.

export default function (state = initialState, action) {
  switch (action.type) {
    case constants.SOME_ACTION:
      return {
        ...state,
        newProperty: action.newProperty
      };

    case constants.ERROR_ACTION:
      return {
        ...state,
        error: action.error
      };

    case constants.MORE_DEEP_ACTION:
      return {
        ...state,
        users: {
          ...state.users,
          user1: action.users.user1
        }
      };

    default:
      return {
        ...state
      }
  }
}

You can then use ES6 spread syntax to return your old state with whatever new properties you want changed/added to it.

You can read more about this approach here... https://redux.js.org/recipes/using-object-spread-operator

答案 2 :(得分:0)

我发现了我真正喜欢的东西:

 import createReducer from 'redux-starter-kit';
 const someReducer = createReducer( initialState, {
    SOME_ACTION: (state) => { /* doing whatever I want with this local State */ },
    SOME_ANOTHER_ACTION: (state) => { /* doing whatever I want with local State */ },
    THIRD_ACTION: (state, action) => { ... }, 
 });

答案 3 :(得分:-2)

If your state has nested objects or arrays, Object.assign or ... will copy references to your older state variable and it may cause some issue. This is the reason why some developers use immutable libraries as in most of the case state has deep nested array or objects.

function someReducer(state = initialState, action) {
   if (action.type === SOME_ACTION) {
       const newState = Object.assign( {}, state );
       // newState can still have references to your older state values if they are array or orobjects

      return newState;
   }   
   return state;
}