这个 redux reducer 可以吗

IT技术 javascript reactjs redux immutability
2021-05-02 06:50:23

这个减速机好吗:

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;
}

如果没问题,为什么我们需要所有这些不可变的库来使我们的生活复杂化。

ps 只是试图理解 Redux 和不变性

4个回答

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 语句的忠实粉丝。

标准方法是在减速器中使用switch/casewith spread 语法 ( ...)。

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
      }
  }
}

然后,您可以使用 ES6 扩展语法返回您的旧状态以及您想要更改/添加的任何新属性。

您可以在此处阅读有关此方法的更多信息... https://redux.js.org/recipes/using-object-spread-operator

我发现了一些我非常喜欢的东西:

 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) => { ... }, 
 });

如果您的状态具有嵌套的对象或数组,Object.assign或者...将复制对旧状态变量的引用,则可能会导致一些问题。这就是为什么一些开发人员使用不可变库的原因,因为在大多数情况下状态具有深度嵌套的数组或对象。

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;
}