我想将一个 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/