javascript - 发送 2 个参数来 React Redux 中间件,而不是只发送一个操作

标签 javascript reactjs redux middleware react-redux

我想将一个 bool 值作为第二个参数传递给我的 actionCreator ,这将确定我的中间件调度什么,但如何让我的中间件访问第二个参数? 我是否必须分派(dispatch)数组或对象而不是 promise ?

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 的成员发生任何碰撞类

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

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

关于javascript - 发送 2 个参数来 React Redux 中间件,而不是只发送一个操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39223460/

相关文章:

javascript - 在 React Native 中使用 map() 列出数组元素

reactjs - React Native 和 Redux : Require cycle (how to get rid of it? )

reactjs - 如何将 React 表单数据添加到 Firebase 实时数据库?

redux - 用户看到深层嵌套状态的一部分,可见属性应该在顶层吗?

Angular NGRX - 为 Redux-Devtools 命名商店/应用程序实例

javascript - 解析iOS SDK : Calling Cloud Functions From Xcode

javascript - 安卓浏览器: avoid keyboard to hide when icon is pressed

javascript - 从中心动画/显示内容

reactjs - 引用错误 : Can't find variable React

reactjs - 在 Redux React 的另一个 Action 中调用一个 Action