让我们换个角度看这个问题。与其问“当路由改变时如何调度操作”,不如问“真相的真正来源是什么:Redux还是URL?”
如果我们一起去
redux
dispatch
一些
action
redux-saga
或
redux-observable
甚至是
redux-thunk
? ) 更改了url:
Comp -> dispatch(action) -> store updates -> URL changes
URL changes -> dispatch(action) -> store updates
如果我们走这条路,这听起来是你想要的,你可能需要连接
middleware
,它们是以下签名的函数:
store => next => action => next(action)
根据您使用的路由器,您可以钩住它们的动作,也可以钩住它们
window.onpopstate
然后检查下一个url。不管怎样,整个中间件功能看起来像
const middleware = store => {
return next => action => {
if (actionWillCauseSpellToBeNeeded(action)) {
makeAPICall()
.then(transformAPIToAction)
.catch(transformError)
.then(store.dispatch)
}
return next(action)
}
}