简体   繁体   English

单个Websocket连接可在组件和存储中使用

[英]Single websocket connection to use across components and store

I have a mobx store which stores all the data from the server. 我有一个mobx存储,用于存储服务器中的所有数据。

// stores.js // stores.js

class User {
    @observable userInfo = null;
    @observable webSocketConnected = false;
}

class Trend {
    @observable latest_trends = null;
}

I have a component to type and send user input to the server via websockets. 我有一个要输入的组件,并通过websocket将用户输入发送到服务器。

@inject('UserStore') @observer
export default class Editor extends React.Component {
    componentDidMount() {
        socket = new WebSocket(newURL);
    }

    sendText = () => {
        // socket.send(...) and update to the store
    }

    render() {
        return (
            <View style={styles.container}>
                ...
                <TextInput
                    value={this.state.text}
                    ...
                    style={styles.text}/>
            </View>
        )
    }

}

I have another component that can vote a user's comment, which I would like to update to the server via websockets. 我还有另一个组件可以投票给用户评论,我想通过websockets更新到服务器。

@inject('TrendStore') @observer
export default class Editor extends React.Component {
    updateComment = () => {
        // socket.send(...)
    }

    render() {
        return (
            <TouchableOpacity onPress={this.updateComment}>
                <Icon/>
            </TouchableOpacity>
        )
    }
}

How can I create one WebSocket connection, so that I can use it with all my store and components? 如何创建一个WebSocket连接,以便可以在所有商店和组件中使用它?

You would create a websocket service class that gets passed to the constructor of every store, that needs access to the websocket. 您将创建一个websocket服务类,该类传递给每个需要访问websocket的商店的构造函数。 In your program's main file you initialize all stores and provide them to the component. 在程序的主文件中,您初始化所有存储并将它们提供给组件。

const webSocketService = new WebSocketService();
const userstore = new UserStore(websocketService);
const trendStore = new TrendStore(websocketservice);
const stores = { userStore, trendStore };
...
<Provider {...stores} >
   ...
</Provider>

The WebSocketService can have methods like WebSocketService可以具有如下方法

  • send(message) 发信息)

  • registerEventListener(event, listener) registerEventListener(事件,监听器)

So you are giving every store the same instance of websocketService. 因此,您要为每个商店提供相同的websocketService实例。

Tip: don't write your sending logic or any other business login in the components. 提示:请勿在组件中编写发送逻辑或任何其他业务登录信息。 Add a method to the specific store like sendMessage(message) and call this method from your component. 将方法添加到特定的存储区(例如sendMessage(message)),然后从组件中调用此方法。

Hope this answers your question. 希望这能回答您的问题。

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

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