发送2个参数来反应redux中间件而不是只有一个动作

时间:2016-08-30 09:18:10

标签: javascript reactjs redux middleware react-redux

我想传入一个布尔值作为我的actionCreator的第二个参数,这将决定我的中间件调度,但是如何让我的中间件访问第二个参数? 我是否必须派遣数组或对象而不是承诺?

export const fetchPokemon = function (pokemonName, booleanValue) {
  return function (dispatch) {
    dispatch({type: 'REQUESTING'})
    const requestURL = `http://pokeapi.co/api/v2/pokemon/${pokemonName}/`
    dispatch(fetch(requestURL))
  }
}

中间件

const fetchPromiseMiddleware = store => next => action => {
  if (typeof action.then !== 'function') {
    return next(action)
  }
  ...
  return response.json()
  }).then(function (data) {
    if booleanValue {
      store.dispatch(receivePokemon(formatPokemonData(data)))
    } else {
      store.dispatch(fetchPokemonDescription(data.name))
    }
  })
}

1 个答案:

答案 0 :(得分:1)

您似乎已经回答了自己,您发送的操作应该包含所有相关数据。 最简单的选项似乎是为您的操作添加一个或多个属性,因为Promise已经是一个对象。

export const fetchPokemon = function (pokemonName, booleanValue) {
  return function (dispatch) {
    dispatch({type: 'REQUESTING'})
    const requestURL = `http://pokeapi.co/api/v2/pokemon/${pokemonName}/`
    dispatch(Object.assign(fetch(requestURL), {
      someNameForYourBooleanParameter: booleanValue
    })
  }
}

const fetchPromiseMiddleware = store => next => action => {
  if (typeof action.then !== 'function') {
    return next(action)
  }
  ...
  return response.json()
  }).then(function (data) {
    if (action.someNameForYourBooleanParameter) {
      store.dispatch(receivePokemon(formatPokemonData(data)))
    } else {
      store.dispatch(fetchPokemonDescription(data.name))
    }
  })
}

如果您想继续此路径,我建议将这些值放在.payload属性下,以防止与Promise类成员发生任何冲突

我进一步采取这种方法,以避免为同一逻辑操作分派多个动作:

export const fetchPokemon = function (pokemonName, booleanValue) {
  return function (dispatch) {
    const requestURL = `http://pokeapi.co/api/v2/pokemon/${pokemonName}/`;
    dispatch({
      type: 'REQUESTING',
      promise: fetch(requestURL),
      payload: {
        someNameForYourBooleanParameter: booleanValue
      }
    })
  }
}