[英]how does dispatch, next, and the ordering of middleware work in react redux?
我正在学习中间件并想确认一些事情。 如果我有以下中间件设置:
dispatch -> thunk -> promise 中间件 -> 流量中间件 -> reducer
我想澄清一些其他的事情。 如果我对以下内容的理解不正确,请告诉我:
如果我调度任何其他函数或承诺,动作将直接转到减速器。
如果我调度一个函数,它会通过 thunk,如果我调用 next 函数,它将通过 promise 中间件。
我的中间件.js
import * as actions from '../actions/actionCreators'
import { formatPokemonData, formatDescription, formatPokeType } from '../helpers/helpers'
import fetch from 'isomorphic-fetch'
export const promiseErrorMiddleware = store => next => action => {
if (!action.promise) {
return next(action)
}
const url = action.url
const fetchName = action.fetchName
return Promise.resolve(fetch(url)).then((response) => {
if (response.status === 404) {
store.dispatch({type: 'SPELLING_ERROR'})
throw new Error("Please ensure Pokemon name is spelled correctly")
} else if (response.status >= 400) {
store.dispatch({type: 'SERVER_ERROR'})
throw new Error("Server Error")
}
return response.json()
}).then((data) => {
next({data: data, needDirection: true, fetchName: fetchName })
})
}
export const dataTrafficMiddleware = store => next => action => {
if (!action.needDirection) {
return next(action)
}
const data = action.data
const fetchName = action.fetchName
if (fetchName === 'fetchPokemon') {
next(actions.receivePokemon(formatPokemonData(data)))
store.dispatch(actions.fetchPokemonDescription(data.name))
} else if (fetchName === 'fetchPokemonDescription') {
store.dispatch(actions.receivePokemonDescription(formatDescription(data)))
store.dispatch(actions.addActivePokemon(store.getState().pokemonArray.filter((p) => (
p.name === data.name
))[0]))
store.dispatch(actions.checkPokeTypeCache(store.getState().activePokemon.pokeType))
} else if (fetchName === 'mainTypeFetch') {
store.dispatch(actions.receivePokeType(formatPokeType(data)))
store.dispatch(actions.addActivePokeType(formatPokeType(data)))
} else if (fetchName === 'subTypeFetch') {
store.dispatch(actions.receivePokeType(formatPokeType(data)))
store.dispatch(actions.addActiveSubPokeType(formatPokeType(data)))
}
}
- 如果我调度任何其他函数或承诺,动作将直接转到减速器。
- 如果我调度一个函数,它会通过 thunk,如果我调用 next 函数,它将通过 promise 中间件。
你在这两点上是正确的。
- 如果我调度一个函数,它会通过 thunk,并且在该函数之外,如果我调度另一个函数,它会再次通过 thunk
redux-thunk
在函数中注入dispatch
,它从链的开始再次启动进程。 因此,如果您将一个函数进行调度,它将再次由thunk
处理。
- 如果我在流量中间件中,调用 next 会将动作带到减速器,或者如果我调用了 dispatch 并且动作既不是函数也不是承诺,它也会直接进入减速器。
很难回答你的问题,因为我不知道你的流量中间件实现
- 如果在 thunk、promise 中间件或流量中间件中,我不使用 dispatch 或 next,那么返回的对象将被切断,循环停止在那里,数据将不再通过任何中间件链,也不会到达减速器。
是的,如果你不调用next
,chain 中的其他中间件将不会得到你的 action,也不会产生任何影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.