Where to put SignalR hub in React/Redux app?

后端 未结 2 1938
走了就别回头了
走了就别回头了 2021-01-02 13:47

I\'m designing a React website using Redux as the state store, which is primarily to display the current population of items to the user, using live updates to update the it

2条回答
  •  猫巷女王i
    2021-01-02 14:25

    Per the Redux FAQ, the right place for websockets and other similar connections is in Redux middleware.

    Here is a list of existing websocket middle-wares. You can look at the source code of a couple of them and very easily get an idea of how to implement your own custom middle-ware:

    A middleware can dispatch actions. Here's an example of what a socket middleware might look like, and dispatching an action that it listens for:

    const createMySocketMiddleware = (url) => {
        return storeAPI => {
            let socket = createMyWebsocket(url);
    
            socket.on("message", (message) => {
                storeAPI.dispatch({
                    type : "SOCKET_MESSAGE_RECEIVED",
                    payload : message
                });
            });
    
            return next => action => {
                if(action.type == "SEND_WEBSOCKET_MESSAGE") {
                    socket.send(action.payload);
                    return;
                }
    
                return next(action);
            }
        }
    }
    

    You need to apply this middleware to your redux store

    let store = createStore(
        some_reducer,
        applyMiddleware(createMySocketMiddleware)
    )
    

    Later, in your app. This is an action creator

    const sendSocketMessage = message => ({
        type : "SEND_WEBSOCKET_MESSAGE",
        payload : message
    }
    

    Add a button in your component to dispatch an action via websockets

    class MyComponent extends React.Component {
        handleClick = () => {
            this.props.sendSocketMessage("This goes to the server");
        }
    }
    
    export default connect(null, {sendSocketMessage})(MyComponent)
    

提交回复
热议问题