首页 > 解决方案 > 反应本机中的连接对象单例

问题描述

我正在尝试创建一个单例服务类,在其中我实例化一个连接到后端的连接对象,以便在每个组件中重用连接对象,所以我这样做了:

const {
Kuzzle,
WebSocket
 } = require('kuzzle-sdk');

class KuzzleService {

static instance = null;
static async createInstance() {
    var object = new KuzzleService();
    object.kuzzle = new Kuzzle(
        new WebSocket('localhost'),{defaultIndex: 'index'}
    );
    await object.kuzzle.connect();
    const credentials = { username: 'user', password: 'pass' };
    const jwt = await object.kuzzle.auth.login('local', credentials);
    return object;
}

static async getInstance () {
    if (!KuzzleService.instance) {
        KuzzleService.instance = await KuzzleService.createInstance();
    }
    return KuzzleService.instance;
}

}
const kuzzleService = KuzzleService.getInstance();
export default kuzzleService;

但是当我在组件中导入服务时,如下所示:

import kuzzleService from "../services/kuzzle-service.js";

我打印:

 async componentDidMount(){
    console.log(JSON.stringify(kuzzleService.kuzzle));
 }

它给了我“未定义”。我应该以另一种方式导入服务吗?

标签: react-nativeservicewebsocketkuzzle

解决方案


这可能是因为当您 export 时kuzzleService, by 给出的承诺.getInstance()尚未解决。

您应该导出.getInstance函数并在中等待它componentDidMount,如下所示:

export default KuzzleService; // export the singleton directly
async componentDidMount(){
    const kuzzle = await KuzzleService.getInstance();
    console.log(kuzzle);
}

推荐阅读