reactjs - react Redux : Should reducers contain any logic

标签 reactjs react-native redux react-redux

我有一个带有添加、更新和删除案例的购物车 reducer 功能。我在 redux 商店中也有一个产品数组。 当有两个项目添加到产品数组时,我会增加数量值,而不是两个项目。我的主要问题是, reducer 是否应该包含任何逻辑,即确定产品数组是否已包含确切的产品并且仅返回产品数量的更新,或者是否应该在表示组件中处理此行为,检查现有产品并添加新产品产品或更新数量?

function CartReducer (state = initialState, action) {
  switch (action.type) {
    case AddToCart:
      return {
        ...state,
        products: [...state.products, action.product],
        totalPrice: state.totalPrice += (action.price * action.quantity)
      }

    case RemoveItemCart:

      return {
        ...state,
        products: [
          ...state.products.slice(0, action.index),
          ...state.products.slice(action.index + 1)
        ]
      }

    case UpdateItemQuantity:
      return {
        ...state,
        products: state.products.map((product, index) => {
          if (index === action.index) {
            return Object.assign({}, product, {
              quantity: action.quantity
            })
          }
          return product
        })
      }

    default:
      return state
  }
}

最佳答案

the Redux FAQ entry on splitting logic between reducers and action creators :

There's no single clear answer to exactly what pieces of logic should go in a reducer or an action creator. Some developers prefer to have “fat” action creators, with “thin” reducers that simply take the data in an action and blindly merge it into the corresponding state. Others try to emphasize keeping actions as small as possible, and minimize the usage of getState() in an action creator. (For purposes of this question, other async approaches such as sagas and observables fall in the "action creator" category.)

There are some potential benefits from putting more logic into your reducers. It's likely that the action types would be more semantic and more meaningful (such as "USER_UPDATED" instead of "SET_STATE"). In addition, having more logic in reducers means that more functionality will be affected by time travel debugging.

This comment sums up the dichotomy nicely:

Now, the problem is what to put in the action creator and what in the reducer, the choice between fat and thin action objects. If you put all the logic in the action creator, you end up with fat action objects that basically declare the updates to the state. Reducers become pure, dumb, add-this, remove that, update these functions. They will be easy to compose. But not much of your business logic will be there. If you put more logic in the reducer, you end up with nice, thin action objects, most of your data logic in one place, but your reducers are harder to compose since you might need info from other branches. You end up with large reducers or reducers that take additional arguments from higher up in the state.

我还写了my own thoughts on "thick and thin" reducers :

There's valid tradeoffs with putting more logic in action creators vs putting more logic in reducers. One good point that I saw recently is that if you have more logic in reducers, that means more things that can be re-run if you are time-travel debugging (which would generally be a good thing).

I personally tend to put logic in both places at once. I write action creators that take time to determine if an action should be dispatched, and if so, what the contents should be. However, I also often write corresponding reducers that look at the contents of the action and perform some complex state updates in response.

更新

截至 2020 年,we specifically recommend putting as much logic as possible in reducers :

Wherever possible, try to put as much of the logic for calculating a new state into the appropriate reducer, rather than in the code that prepares and dispatches the action (like a click handler). This helps ensure that more of the actual app logic is easily testable, enables more effective use of time-travel debugging, and helps avoid common mistakes that can lead to mutations and bugs.

There are valid cases where some or all of the new state should be calculated first (such as generating a unique ID), but that should be kept to a minimum.

关于reactjs - react Redux : Should reducers contain any logic,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47227419/

相关文章:

javascript - 嵌套参数的 ES6 对象解构默认值

javascript - React-Redux 中的 mapStateToProps 中的状态参数是什么

javascript - 如何在使用 isomorphic-fetch 进行异常处理 promise 后解析 json

react-native - 如何从 React Native Picker 获取值和标签名称?

javascript - 传递 props react-native-router-flux 时防止场景转换

android - 如何同步 PostgreSQL 数据和 React Native 移动应用程序数据?

reactjs - 将 redux 与本地数据库结合使用

reactjs - 使用 React Native CLI 时应用程序构建失败

reactjs - 在react-admin中通过REST API进行基于cookie的身份验证

javascript - 由渲染更新的 ReactJS Cortex 对象未调用?