Javascript 在react redux中,中间件的分派、下一步和排序是如何工作的?
我正在学习中间件,想确认一下。如果我有以下中间件设置: dispatch->thunk->promise中间件->流量中间件->reducer 我想澄清其他一些事情。如果我对以下内容的理解不正确,请告知我:Javascript 在react redux中,中间件的分派、下一步和排序是如何工作的?,javascript,redux,middleware,react-redux,Javascript,Redux,Middleware,React Redux,我正在学习中间件,想确认一下。如果我有以下中间件设置: dispatch->thunk->promise中间件->流量中间件->reducer 我想澄清其他一些事情。如果我对以下内容的理解不正确,请告知我: 如果我分派任何其他函数或承诺,则操作将直接转到减速机 如果我分派一个函数,它将通过thunk,在该函数之外,如果我调用next,它将通过promise中间件 如果我分派一个函数,它将通过thunk,在这个函数之外,如果我分派另一个函数,它将再次通过thunk,或者如果我分派一个承诺,它将通过
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)))
}
}
redux thunk
在函数中注入dispatch
,该函数从链的开始处再次启动流程。因此,如果要分派一个函数,它将再次由thunk
处理
是的,如果你不调用
next
,链中的其他中间件将不会得到你的操作,也不会有任何效果。我已经在我的middleware.js中放置了流量中间件,尽管我不认为我的流量中间件有什么特别之处。我的问题是,你可以看到我在使用store.dispatch,很多动作都是直接进入商店的,所以这意味着我应该可以使用next而不是dispatch,对吗?因为我的流量中间件是数据到达reducer之前的最后一层中间件?