【问题标题】:What does it mean for an action to travel through an entire middleware chain in redux?在 redux 中,一个动作穿过整个中间件链意味着什么?
【发布时间】:2016-12-31 03:02:31
【问题描述】:

看看react-redux docs,我不明白为什么让一个动作遍历整个中间件会有用:

它确实有点诡计,以确保如果你打电话 store.dispatch(action) 从你的中间件而不是 next(action), 该动作实际上将再次遍历整个中间件链, 包括当前的中间件。这对异步很有用 中间件,就像我们之前看到的那样。

动作通过中间件是什么意思?这对派送有何影响?我的理解是dispatch会通过它所经过的每一层中间件发生变化,next指的是之前中间件的dispatch,而dispatch指的是原来的store.dispatch。

【问题讨论】:

    标签: javascript reactjs redux middleware react-redux


    【解决方案1】:

    正如您在middleware example 中看到的,有多个中间件项可以创建管道:

    rafScheduler -> timeoutScheduler -> thunk -> vanillaPromise -> etc...

    在到达基本 reducer 或被其中一个中间件项拦截之前,动作会遍历所有中间件项。每个中间件项可以决定通过使用next() 将操作移动到链中的下一个中间件。但是,有时我们希望动作从一开始就在链中传播。

    例如,使用 redux thunk,我们调度了一个异步操作,该操作将由 thunk 中间件处理。当异步调用成功时,异步操作将调度另一个操作。此操作应使用rafScheduler 中间件重新开始。

    如果调度会像下一个一样工作,它将转而前往vanillaPromise 中间件。为了解决这个问题,dispatch(action),无论在哪里调用,总是从一开始就遍历链。

    要创建此行为 applyMiddleware() 运行中间件 store => next => action 方法,将 middlewareAPI api 传递给 store 参数,传递并覆盖 store.dispatch,新的调度是 @987654322 @中间件。这就是魔法发生的地方 - 新的调度是中间件方法链,每个调用 next 时调用它之后的一个(next = 下一个中间件方法),最后一个 next() 是旧的 store.dispatch调用基本减速器:

    export default function applyMiddleware(...middlewares) {
      return (createStore) => (reducer, preloadedState, enhancer) => {
        var store = createStore(reducer, preloadedState, enhancer)
        var dispatch = store.dispatch // this is the original dispatch
        var chain = []
    
        /*** this the store param of the middleware ***/
        var middlewareAPI = {
          getState: store.getState,
          dispatch: (action) => dispatch(action) 
        }
    
        /*** store param is applied to old middlewares to create the chain ***/
        chain = middlewares.map(middleware => middleware(middlewareAPI))
    
        /*** The chain is composed. For all methods in the chain, but the last, next() is the middleware method after it in the chain, the last next is store.dispatch ***/
        dispatch = compose(...chain)(store.dispatch)
    
        return {
          ...store, 
          dispatch // the new dispatch is returned instead of the old
        }
      }
    }
    

    【讨论】:

    • “每个中间件项都可以决定使用 next() 将操作移动到链中的下一个中间件”是什么意思?我认为下一个是指来自先前中间件的调度?它用作指向上一次调度的指针,因为文档使用了let next = store.dispatch
    • 文档指的是单个中间件,而不是它们的链。在组合链中,next() 指的是中间件方法,它是链中当前项之后的那个。只有最后一个next其实是store.dispatch
    • @OriDrori 你介意看看stackoverflow.com/questions/42217369/…吗?
    猜你喜欢
    • 1970-01-01
    • 2010-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-12
    • 2010-10-31
    相关资源
    最近更新 更多