reactjs - 在哪里存储 Class 实例以实现 Redux 中的可重用性?

标签 reactjs redux redux-saga

我正在尝试在我的 React/Redux/redux saga 应用程序中实现 Pusher 的消息传递库 Chatkit,而且我是 Redux 的新手。连接到 chatkit 的代码如下所示:

const chatManager = new ChatManager({
    instanceLocator: 'v1:us1:80215247-1df3-4956-8ba8-9744ffd12161',
    userId: 'sarah',
    tokenProvider: new TokenProvider({ url: 'your.auth.url' })
})

chatManager.connect()
    .then(currentUser => {
        console.log('Successful connection', currentUser)
    })
    .catch(err => {
        console.log('Error on connection', err)
    })

我需要全局存储 chatManager 和 currentUser 对象(它们是带有附加函数的复杂类的实例),以便我稍后可以再次使用它们来加入房间、订阅事件等。

我的第一个想法是我应该将它存储在 Redux 中,因为那现在是我的“全局存储”,但后来我意识到它可能不起作用,因为它不会是我从存储中返回的原始对象,它可能是一个克隆。然后我读到显然只有普通对象才应该存储在 Redux 中。

那么,那些不是普通对象但需要全局存储的东西在哪里呢?我不想将它们放在窗口对象上,因为我可能会将其转换为 React Native 应用程序,而且无论如何它看起来都很困惑。

最佳答案

根据 Redux FAQ entry on storing "connection"-type objects :

Middleware are the right place for persistent connections like websockets in a Redux app, for several reasons:

  • Middleware exist for the lifetime of the application
  • Like with the store itself, you probably only need a single instance of a given connection that the whole app can use
  • Middleware can see all dispatched actions and dispatch actions themselves. This means a middleware can take dispatched actions and turn those into messages sent over the websocket, and dispatch new actions when a message is received over the websocket.
  • A websocket connection instance isn't serializable, so it doesn't belong in the store state itself​

编辑

这是我的“示例套接字中间件”示例,已更新为延迟创建套接字,直到它看到登录操作:

const createMySocketMiddleware = (url) => {
    let socket;

    return storeAPI => next => action => {
        switch(action.type) {
            case "LOGIN" : {
                socket = createMyWebsocket(url);

                socket.on("message", (message) => {
                    storeAPI.dispatch({
                        type : "SOCKET_MESSAGE_RECEIVED",
                        payload : message
                    });
                });
                break;
            }
            case "SEND_WEBSOCKET_MESSAGE": {
                socket.send(action.payload);
                return;
            }
        }

        return next(action);
    }
}

关于reactjs - 在哪里存储 Class 实例以实现 Redux 中的可重用性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51831824/

相关文章:

reactjs - redux-saga-test-plan put 效果不匹配,但实际和预期的有效载荷相等

reactjs - 如何使用 redux thunk 在成功或错误后重定向?

reactjs - Hook 不重新渲染组件

javascript - React javascript 中的过程和方法是什么?

reactjs - 如何修复在 redux-saga 中调用 takeEvery() 时发生的 TypeScript 错误?

javascript - 处理响应 - SyntaxError : Unexpected end of input when using mode: 'no-cors'

react-router redux 我如何更新页面加载状态以进行身份​​验证

javascript - Reactjs Redux Actions 必须是普通对象

redux - Yield 调用返回未定义的而不是已解决的 Promise 值

typescript - Redux 传奇使用具有通用函数类型 typescript 的调用效果