将 Redux 转换为 React 上下文 API + useReducer

Converting Redux to React Context API + useReducer

我正在将我的 redux 结构转换为 Context API 结合 useReducer。一切都按预期工作,但是我有一个 web 套接字中间件,我用 applyMiddlewareredux-thunk 绑定到 redux。真的很困惑如何绑定中间件以与我的结构一起工作。

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];
};

我是这样绑定provider的:

  <MonitoringProvider middleware={reducerSocketMiddleware}> // This is the socketFunction provided below
      <Layout /> // This is a component that handles all the routing
   </MonitoringProvider>

我想绑定 socketFunction 中间件。现在,none 分派的操作正在通过此中间件。

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)

解决了问题。