我正在使用Redux +中间件创建聊天应用程序,并且希望在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;
};
Run Code Online (Sandbox Code Playgroud)
}
如果像这样应用我的中间件:
const store = createStore(
reducer,
applyMiddleware(thunk, chatMiddleware)
)
Run Code Online (Sandbox Code Playgroud)
我想传递存储对象,storage但是在文档中找不到任何如何传递附加参数的方法。我怎样才能做到这一点?
您需要再添加一层功能嵌套才能使其正常工作。 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))
)
Run Code Online (Sandbox Code Playgroud)