如何在react-redux中重用动作创建者?

时间:2018-05-06 03:11:48

标签: reactjs redux higher-order-functions reducers

我的问题是如何构建reducer和actions创建器以便正确地重用它们。 我已经在网上阅读了大量关于减速器组合和高阶减速器的参考书目,并设法通过创建一个命名空间的减速器工厂/发电机来实现正确的方向。通过这个,我可以拥有具有独立状态的相同组件/视图的不同实例,这些实例共享共同的行为。但是,对于具有共同点但不相同的组件/视图而言,情况并非如此。让我们说......实体的展示和编辑视图。

在mount上,这两个组件都需要以相同的方式从API获取实体数据,但show组件的功能比编辑组件少得多,编辑组件也处理表单提交,处理错误等...... / p>

所以,说过......我想如何扩展editEntityReducer和editEntity动作创建者以包含entityReducer和实体动作创建者以及编辑自己的reducer特征和动作创建者?

这是我到目前为止,以用户实体为例:

用户缩减器+动作创建者(user.js):

import normalize from 'jsonapi-normalizer'
import { api, authenticatedHeaders } from 'api'
import { RSAA } from 'redux-api-middleware'
import { List, Record } from 'immutable'
import * as constants from './constants'

// ------------------------------------
// Actions
// ------------------------------------
export const destroyUser = (userId) => {
  // Uses redux-api-middleware. see: https://github.com/agraboso/redux-api-middleware
  return {
    [RSAA]: {
      endpoint: api.users.destroy.path(userId),
      method: api.users.destroy.method,
      headers: (state) => authenticatedHeaders(state.session.authorization.token),
      types: [
      constants.DESTROY_START,
      constants.DESTROY_SUCCESS,
      constants.DESTROY_FAIL]
    }
  }
}

export const fetchUser = (userId) => {
  // Uses redux-api-middleware. see: https://github.com/agraboso/redux-api-middleware
  return {
    [RSAA]: {
      endpoint: api.users.show.path(userId),
      method: api.users.show.method,
      headers: (state) => authenticatedHeaders(state.session.authorization.token),
      types: [
      constants.FETCH_START,
      {
        type: constants.FETCH_SUCCESS,
        payload: (action, state, res) => {
          return res.json().then(json => normalize(json))
        }
      },
      constants.FETCH_FAIL]
    }
  }
}

// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = (prefix) => {
  return {
    [`${prefix}_${constants.DESTROY_START}`]: (state, action) => {
      return state.set('destroying', true)
    },

    [`${prefix}_${constants.DESTROY_SUCCESS}`]: (state, action) => {
      return state.set('destroying', false)
    },

    [`${prefix}_${constants.DESTROY_FAIL}`]: (state, action) => {
      return state.set('destroying', false)
    },

    [`${prefix}_${constants.FETCH_START}`]: (state, action) => {
      return state.set('loading', true)
    },

    [`${prefix}_${constants.FETCH_SUCCESS}`]: (state, { payload }) => {
      const users = payload.entities.user
      const userIds = payload.result.user
      const roles = payload.entities.role

      // It's a single record fetch
      const user = users[userIds[0]]

      return state.merge({
        loading: false,
        record: Record({ user: Record(user)(), roles: Record(roles)() })()
      })
    },

    [`${prefix}_${constants.FETCH_FAIL}`]: (state, action) => {
      return state.set('loading', false)
    }
  }

}

// ------------------------------------
// Reducer
// ------------------------------------
const initialState = Record({
  destroying: false,
  loading: true, // initially true so will only go to false upong user loaded
  record: Record({ user: Record({})(), roles: List([]) })()
})()

const userReducer = (prefix = 'USER') => {
  if (prefix === undefined || prefix.length < 1) {
    throw new Error('prefix must be defined')
  }

  return (state = initialState, action) => {
    const handler = ACTION_HANDLERS(prefix)[`${prefix}_${action.type}`]
    return handler ? handler(state, action) : state
  }
}

export default userReducer

编辑用户缩减器和动作创建器(edit_user.js):

import normalize from 'jsonapi-normalizer'
import { api, authenticatedHeaders } from 'api'
import { RSAA } from 'redux-api-middleware'
import { List, Record } from 'immutable'
import * as constants from './constants'

// ------------------------------------
// Actions
// ------------------------------------
export const updateUser = (userId, params = {}) => {
  // Uses redux-api-middleware. see: https://github.com/agraboso/redux-api-middleware
  return {
    [RSAA]: {
      endpoint: api.users.update.path(userId),
      method: api.users.update.method,
      headers: (state) => authenticatedHeaders(state.session.authorization.token),
      types: [
      constants.USER_UPDATE_START,
      constants.USER_UPDATE_SUCCESS,
      constants.USER_UPDATE_FAIL]
    }
  }
}

// TODO: see how to reuse this from the user.js file!
export const fetchUser = (userId) => {
  // Uses redux-api-middleware. see: https://github.com/agraboso/redux-api-middleware
  return {
    [RSAA]: {
      endpoint: api.users.show.path(userId),
      method: api.users.show.method,
      headers: (state) => authenticatedHeaders(state.session.authorization.token),
      types: [
      constants.USER_FETCH_START,
      {
        type: constants.USER_FETCH_SUCCESS,
        payload: (action, state, res) => {
          return res.json().then(json => normalize(json))
        }
      },
      constants.USER_FETCH_FAIL]
    }
  }
}

// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
  [constants.USER_UPDATE_START]: (state, action) => {
    return state.set('loading', true)
  },

  [constants.USER_UPDATE_SUCCESS]: (state, action) => {
    return state.set('loading', false)
  },

  [constants.USER_UPDATE_FAIL]: (state, action) => {
    return state.set('loading', false)
  },

  // TODO: this reducers are the same as user.js, reuse them!!
  [constants.USER_FETCH_START]: (state, action) => {
    return state.set('loading', true)
  },

  [constants.USER_FETCH_SUCCESS]: (state, { payload }) => {
    const users = payload.entities.user
    const userIds = payload.result.user
    const roles = payload.entities.role

    // It's a single record fetch
    const user = users[userIds[0]]

    return state.merge({
      loading: false,
      record: Record({ user: Record(user)(), roles: Record(roles)() })()
    })
  },

  [constants.USER_FETCH_FAIL]: (state, action) => {
    return state.set('loading', false)
  }

}

// ------------------------------------
// Reducer
// ------------------------------------
const initialState = Record({
  loading: true, // initially true so will only go to false upong user loaded
  record: Record({ user: Record({})(), roles: List([]) })()
})()

export default function editUserReducer (state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]

  return handler ? handler(state, action) : state
}

正如您在代码中的TODO中所看到的,我希望能够重用reducer和action creator的那些部分,因为它不仅可以重用于实体基本操作,而且适用于任何实体我的应用程序可能使用的任何资源上的通用CRUD操作!

由于

1 个答案:

答案 0 :(得分:0)

您可以创建一个新函数,并将差异(从我可以看到的,常量)提取到参数中,或者作为高阶函数(就像我在下面所做的那样),或者将它们与现有参数组合( userId):

export const createFetchUser = (fetchStart, fetchSuccess, fetchFail) => userId =>
  // Uses redux-api-middleware. see: https://github.com/agraboso/redux-api-middleware
  ({
    [RSAA]: {
      endpoint: api.users.show.path(userId),
      method: api.users.show.method,
      headers: state => authenticatedHeaders(state.session.authorization.token),
      types: [
        fetchStart,
        {
          type: fetchSuccess,
          payload: (action, state, res) => res.json().then(json => normalize(json)),
        },
        fetchFail,
      ],
    },
  });

然后,您可以在user.jsedit_user.js中导入此功能,以便为不同的常量创建fetchUser函数,例如。 user.js

export const fetchUser = userId =>
  createFetchUser(constants.FETCH_START, constants.FETCH_SUCCESS, constants.FETCH_FAIL);

你可以为减速器做类似的事情。