【问题标题】:My redux reducers all look the same. Am I doing it wrong?我的 redux reducer 看起来都一样。我做错了吗?
【发布时间】:2017-09-07 09:58:29
【问题描述】:

我正在使用 Redux 构建一个非常简单的应用程序,而我的 reducer 看起来都很相似。从技术上讲,它可以工作,但这是很多代码重复。

// The employees reducer
export default (state = initialState, action) => {
  switch (action.type) {
    case EMPLOYEES_REQUEST:
      return [ ...state, { isFetching: true } ]
    case EMPLOYEES_SUCCESS:
      // DEBUG
      console.log('Dispatching employees');
      console.log(action.response);
      // END DEBUG

      // Return employees directly in the employees state
      return { ...state, list: JSON.parse(action.response) };
    case EMPLOYEES_FAILURE:
      return [ ...state, { isFetching: false } ]
    default:
      return state
    }
}

还有

// The services reducer
export default (state = initialState, action) => {
  switch (action.type) {
    case SERVICES_REQUEST:
      return [ ...state, { isFetching: true } ]
    case SERVICES_SUCCESS:
      // DEBUG
      console.log('Dispatching services');
      console.log(action.response);
      // END DEBUG

      // Return services directly in the services state
      return { ...state, list: JSON.parse(action.response) };
    case SERVICES_FAILURE:
      return [ ...state, { isFetching: false } ]
    default:
      return state
    }
}

我可以使用具有不同操作的通用减速器吗?

谢谢!

【问题讨论】:

  • 只是我的 0.02 美元,您不应该使用真正使用相同的密钥,例如,当您调用 SERVICE_SUCCESSEMPLOYEES_SUCCESS 时,您再次使用密钥 list。没有办法区分员工列表和服务列表。你应该支持employeeListserviceList IMO。与isFetching 相同 - 你在拿什么?这还不是很清楚。 isFetchingEmployeeisFetchingService 有助于缓解任何混乱。

标签: reactjs redux react-redux redux-thunk


【解决方案1】:

Reducer 只是一个函数。你总是可以使用高阶函数来实现它。

const makeListReducer = (initial, prefix) => (state = initial, action) => {
  switch(action.type) {
    case `${prefix}_REQUEST`: return {...state, isFetching: true}
    case `${prefix}_SUCCESS`: return {...state, isFetching: false, list: JSON.parse(action.response)}
    case `${prefix}_FAILURE`: return {...state, isFetching: false, /*etc*/}
  }

  return state
}

// The employees reducer
export default makeListReducer(initialState, 'EMPLOYEES')

【讨论】:

    猜你喜欢
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 2021-12-04
    • 1970-01-01
    相关资源
    最近更新 更多