reactjs - 将 Redux 转换为 React Context API + useReducer
问题描述
我正在将我的 redux 结构转换为 Context API 并结合useReducer
. 一切都按预期工作,但是我有一个 web socket 中间件,我用applyMiddleware
and绑定到 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.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
中间件。现在,分派的所有动作都没有通过这个中间件。
套接字功能:
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)
解决了这个问题。
推荐阅读
- azure - 如何为 DCU 百分比指标警报选择正确的阈值?
- javascript - 使用 Laravel 清除缓存
- python - python中负索引的意义是什么?
- javascript - 更改 react mateial-ui Select MuiList 的 backgroundColor
- python - 在python中查找具有lookthru路径和其他列的孩子的所有父母
- node.js - 在电子构建中找不到应用程序入口文件“./main.js”
- date - 为什么我的公式返回的是数字而不是日期?
- python - 我无法从列表中删除元素
- actions-on-google - 动作使麦克风保持打开状态
- pine-script - 警报,真或假,从真到假,从假到真