2016-11-21 21 views
1

我創造與終極版+中間件聊天應用,並想用中間件存儲對象在本地存儲對象每當ADD_MESSAGE動作被分派:終極版中間件:如何通過額外的參數中間件

export function storageMiddleware(store) { 
return next => action => { 
    const result = next(action); 
    if (action.type === "ADD_MESSAGE") { 
     // Add to my storage object here 
    } 

    return result; 
}; 

}

如果我的應用中間件,像這樣:

const store = createStore(
    reducer, 
    applyMiddleware(thunk, chatMiddleware) 
) 

我想在我的存儲對象通過,storage,但在文檔中找不到其他參數的任何地方。我怎樣才能做到這一點?

回答

2

您需要添加一個更多級別的函數嵌套才能使其工作。 redux-thunk做同樣的事情:

// Middleware definition 
function createThunkMiddleware(extraArgument) { 
    return ({ dispatch, getState }) => next => action => { 
    if (typeof action === 'function') { 
     return action(dispatch, getState, extraArgument); 
    } 

    return next(action); 
    }; 
} 

const thunk = createThunkMiddleware(); 
thunk.withExtraArgument = createThunkMiddleware; 

// Middleware usage 
const store = createStore(
    reducer, 
    applyMiddleware(thunk.withExtraArgument(api)) 
)