我正在将我的redux结构转换为结合useReducer
的上下文API。一切都按照预期工作,但是我有一个web套接字中间件,我绑定了applyMiddleware
和redux-thunk
。我真的很困惑如何将中间件绑定到我的结构中。
MyContext.js
import { createContext } from 'react'
export const initialState = {
values : {}
}
export const Context = createContext(initialState)
MyProvider.js
import { monitoring } from './reducers/monitoring'
import { Context, initialState } from './monitoringContext'
import { useReducerWithMiddleware } from './reducerMiddleware'
export const MonitoringProvider = ({ middleware, children }) => {
const [state, dispatch] = useReducerWithMiddleware(monitoring, initialState, middleware)
return (
<Context.Provider value={{ state, dispatch }}>
{children}
</Context.Provider>
)
}
useReducerMiddleware.js(这里实现了类似redux-thunk
的结构)
import { useReducer } from "react";
export const useReducerWithMiddleware = (reducer, initialState, middleware) => {
const [state, dispatch] = useReducer(reducer, initialState);
const thunkDispatch = action => {
if (typeof action === "function") {
return action(thunkDispatch, state)
}
return middleware(dispatch(action))
};
return [state, thunkDispatch];
};
我这样绑定提供商:
<MonitoringProvider middleware={reducerSocketMiddleware}> // This is the socketFunction provided below
<Layout /> // This is a component that handles all the routing
</MonitoringProvider>
我想绑定socketFunction
中间件。现在,分派的动作都没有经过这个中间件。
socketFunction:
const socketFunction = store => next => action => {
debugger // No visits to this debugger
if (action.type === SOCKET_ACTION_TYPES.CONNECT_SOCKET_IO) {
/* Connect socket */
} else if (action.type === SOCKET_ACTION_TYPES.DISCONNECT_SOCKET_IO) {
if (socket) socket.close(CLOSE_SIG)
} else {
return next(action)
}
}
我没有恰当地调用中间件。
middleware(state)(dispatch)(action)
解决了问题。