简体   繁体   English

如何在 react-native 中调用另一个纯类中的方法?

[英]How can I call the methods in another pure class in react-native?

I got a class to help websocket communication as a single file, here's the code(note this class not extends component):我有一个类来帮助 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;

Then i import it in APP.js to make a connect.然后我将它导入到 APP.js 中以进行连接。 I put it in the componentDidMount() function as follow:我把它放在 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);

    }

But when I run on my Android device, it show ws.initWebSocket is not a function.但是当我在我的 Android 设备上运行时,它显示 ws.initWebSocket 不是一个函数。 wrong info So how to use a pure class in react native?错误信息那么如何在 react native 中使用纯类呢? Or there is not a pure class in React?或者 React 中没有纯类? Thanks!谢谢!

Would be happening 2 things.会发生两件事。

A) You have not imported the class. A) 您尚未导入该课程。

B) When you create a new WebSocketClient you use it with the first letter in lowercase. B) 当你创建一个新的 WebSocketClient 时,你使用它的第一个字母小写。 Should be:应该:

        const ws = new WebSocketClient();

instead of what you have that is而不是你所拥有的

        const ws = new webSocketClient();

note the change: w => W注意变化: w => W

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

相关问题 如何在 class 组件中使用导航? REACT-NATIVE - How can I use navigation in a class component? REACT-NATIVE 如何使用另一个js类n-native-native的键从const中获取值? - How can i fetch a value from a const using a key from another js class n react-native? 如何从无渲染类 React-Native 调用函数 - How to call function from renderless class React-Native 如何在渲染方法React-Native上调用数组对象中的rowData值 - How can i call rowData value in array object on Render Method React-Native 如何从 onPress 调用方法 on Alert 功能 [React-Native] - How can I call method from onPress on Alert function [React-Native] 如何导航到 react-native 中的另一个屏幕 - how to can navigate to another screen in react-native 如何在反应原生中按下按钮时将按钮的当前图像更改为另一个图像 - How can I change the present image of the button to another image on button press in react-native 在 React-Native 中,如何根据我的环境文件选择资产文件夹而不是另一个文件夹? - In React-Native, how can I choose an assets folder instead of another one based on my environment file? 我如何在无状态函数 React-Native 中使用 refs,我正在使用 React-Native 0.62.2 - How can i user refs in stateless functions React-Native, am using React-Native 0.62.2 我如何在课堂上使用 CREATESTACKNAVIGATOR? 反应本机 - HOW DO I USE CREATESTACKNAVIGATOR IN CLASS? REACT-NATIVE
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM