首页 > 解决方案 > 将 Redux 转换为 React Context API + useReducer

问题描述

我正在将我的 redux 结构转换为 Context API 并结合useReducer. 一切都按预期工作,但是我有一个 web socket 中间件,我用applyMiddlewareand绑定到 redux 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.jsredux-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中间件。现在,分派的所有动作都没有通过这个中间件。

套接字功能

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)
    }
}

标签: reactjsreduxreact-hooksmiddleware

解决方案


我没有适当地调用中间件。

middleware(state)(dispatch)(action)

解决了这个问题。


推荐阅读