React Native 中的 Connexion 对象单例

Connexion object singleton in react native

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

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));
 }

它给了我 "undefined"。我应该以其他方式导入服务吗?

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

您应该导出 .getInstance 函数并在 componentDidMount 中等待它,就像这样:

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