简体   繁体   English

Redux 工具包 + Signalr

[英]Redux-toolkit + Signalr

What is the best way to update the state with signalr?用 signalr 更新 state 的最佳方法是什么? At this moment I dispatching data inside on method callback and accessing it using useSelector inside other component.此时我on方法回调中调度数据并在其他组件中使用useSelector访问它。 I wonder if this is the optimal approach.我想知道这是否是最佳方法。

useEffect(()=> {

 const connection = $.hubConnection("http://x.x.x.x/signalr", { useDefaultPath: false })
 const proxy = connection.createHubProxy("exampleHub")

 proxy.on("action", function(data) {
   dispatch(setStatus(data))
 }
})

Slice.js:切片.js:

export const monitorSlice = createSlice({
  name: "example",
  initialState: { 
    status: {},
},
  reducers: {
    setStatus(state, {payload}) => {
      state.status = payload
    }
  }
});

Your approach will work, Here is other approach that you can have:您的方法将起作用,这是您可以采用的其他方法:

Using your own middleware使用自己的中间件

Another approach that is more agnostic is to use a middleware另一种更不可知的方法是使用中间件

import { Middleware } from 'redux'
import { monitorActions } from './monitorSlice';
 
const monitorMiddleware: Middleware = store => next => action => {
  if (!monitorActions.startConnecting.match(action)) {
    return next(action);
  }

  const connection = $.hubConnection("http://x.x.x.x/signalr", { useDefaultPath: false })
  const proxy = connection.createHubProxy("exampleHub")

  proxy.on("action", function(data) {
    dispatch(setStatus(data))
  });
 
  next(action);
}
 
export default monitorMiddleware;

Then inside your react app when you want to establish the connection然后在您想要建立连接时在您的反应应用程序中

useEffect(()=> {
   dispatch(monitorActions.startConnecting())
}, [])

Then when you setup your store, do not forget to add your new middleware monitorMiddleware :然后,当您设置商店时,不要忘记添加新的中间件monitorMiddleware

export const store = configureStore({
  reducer: rootReducer,
  middleware: (getDefaultMiddleware) => {
    return getDefaultMiddleware().concat([monitorMiddleware])
  },
});

Using create api使用创建 api

Another approach is to use createApi .另一种方法是使用createApi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM