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

Send 2 arguments to react redux middleware instead of just one action

我想传递一个布尔值作为我的 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))
    }
  })
}

看来你已经自己回答了,你发送的动作应该包含所有相关数据。 最简单的选择似乎是向您的操作添加 属性(或属性),因为 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 [=23= 的成员发生任何冲突]

我会进一步采用这种方法来避免为同一逻辑操作分派多个操作:

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