react-native - 反应本机中的连接对象单例
问题描述
我正在尝试创建一个单例服务类,在其中我实例化一个连接到后端的连接对象,以便在每个组件中重用连接对象,所以我这样做了:
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));
}
它给了我“未定义”。我应该以另一种方式导入服务吗?
解决方案
这可能是因为当您 export 时kuzzleService
, by 给出的承诺.getInstance()
尚未解决。
您应该导出.getInstance
函数并在中等待它componentDidMount
,如下所示:
export default KuzzleService; // export the singleton directly
async componentDidMount(){
const kuzzle = await KuzzleService.getInstance();
console.log(kuzzle);
}
推荐阅读
- angular - 刷新通过 firebase google 身份验证收到的 Google Id_token
- javascript - 可观察的主题事件监听器
- javascript - 通过 Esc 键关闭确认对话框后无法输入文本
- r - 如何将点击侦听器附加到 DT 和 Shiny 中的数据表?
- javascript - 检查放大数据存储操作的状态
- java - 错误:android.widget.RelativeLayout 无法转换为 androidx.recyclerview.widget.RecyclerView
- android - Android 10蓝牙断开后台服务
- laravel - Flutter App 中无法监听来自 Laravel 服务器的 Socket IO
- docker - 在容器优化操作系统中以 JSON 形式注入日志
- c++ - 如何检查模板中发送的参数类型?