首页 > 解决方案 > 如何在 react-native 中调用另一个纯类中的方法?

问题描述

我有一个类来帮助 websocket 通信作为单个文件,这是代码(注意这个类不扩展组件):

import {
    DeviceEventEmitter,
} from 'react-native';
import { observer, inject } from 'mobx-react';

let that = null;
class WebSocketClient {
    constructor() {
        this.ws = null;
        that = this;
        this.prefixUrl = this.props.globalVarStore.serverAddr + 'ws/chat/' + this.genId() + '/';
    }

    /**
     * get WebSocket instance
     * @returns {WebSocketClient}
     */
    static getInstance() {
        if (!this.instance) {
            this.instance = new WebSocketClient();
        }
        return this.instance;
    }

    /**
     * generate uuid
     */
    static genId() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0,
                v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        }).toUpperCase();
    }

    /**
     * initialize WebSocket
     */
    initWebSocket() {
        try {

            this.timer && clearInterval(this.timer);
            this.ws = new WebSocket(this.prefixUrl);
            this.initWsEvent();
        } catch (e) {
            console.log('WebSocket err:', e);

            this.reconnect();
        }
    }

    /**
     * initialize WebSocket events
     */
    initWsEvent() {

        this.ws.onopen = function () {
            console.log('WebSocket:', 'connect to server');
        };

        this.ws.onmessage = function (evt) {
            if (evt.data !== 'pong') {

                console.log('WebSocket: response msg', evt.data);

                DeviceEventEmitter.emit('pushEmitter', '');

            } else {
                console.log('WebSocket: response pong msg=', evt.data);
            }
        };


        this.ws.onerror = function (err) {
            console.log('WebSocket:', 'connect to server error');

            that.reconnect();
        };

        this.ws.onclose = function () {
            console.log('WebSocket:', 'connect close');

            that.reconnect();
        };


        this.timer = setInterval(() => {
            if (this.ws && this.ws.readyState === WebSocket.OPEN) {
                console.log('WebSocket:', 'ping');
                this.ws.sendMessage('ping');
            }
        }, 15000);
    }


    sendMessage(msg) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            try {
                this.ws.send(msg);
            } catch (err) {
                console.warn('ws sendMessage', err.message);
            }
        } else {
            console.log('WebSocket:', 'connect not open to send message');
        }
    }


    reconnect() {
        if (this.timeout) {
            clearTimeout(this.timeout);
        }
        this.timeout = setTimeout(function () {

            this.initWebSocket();
        }, 15000);
    }
}

export default WebSocketClient;

然后我将它导入 APP.js 进行连接。我把它放在 componentDidMount() 函数中,如下所示:

componentDidMount() {
        const ws = new webSocketClient();
        ws.initWebSocket();
        ws.initWsEvent();
        //Here I want to save the instance in the mobx so i can easily get it and send message
        this.props.messageStore.saveWs(ws);

    }

但是当我在我的 Android 设备上运行时,它显示 ws.initWebSocket 不是一个函数。 错误信息 那么如何在 react native 中使用纯类呢?还是 React 中没有纯类?谢谢!

标签: javascriptreactjsreact-native

解决方案


会发生两件事。

A)您尚未导入该课程。

B)当您创建一个新的 WebSocketClient 时,您使用它的第一个字母为小写。应该:

        const ws = new WebSocketClient();

而不是你所拥有的是

        const ws = new webSocketClient();

注意变化:w => W


推荐阅读