The story:

在react-native 应用程序中,我们使用react-native-sqlite-storage在iOS和Android上处理sqlite3.

该插件使我们能够以这种方式处理本机sqlite实现:

var db = SQLite.openDatabase("test.db".....);

跨多个组件共享db实例的最佳方法是什么?为了提供更多细节,但这不是这个问题的一部分,我们使用redux并有许多操作文件.他们中的一些人也需要访问数据库.

为了处理跨越所有组件和操作的单一sqlite开放实例,以及与本机组件更松散地耦合,我构建了一个封装存储插件的类DataStorage.此类持有sqlite数据库的一个实例(使用react-native sqlite存储),并为应用程序提供方便的方法,如"getUserByName()"、"getAllItems"等.

对于这个DataStorage类的avoid multiple instances个及其内部sqlite db实例,我执行了以下操作:

  1. 构建数据存储类
  2. 创建仅驻留在数据存储中的全局变量.js
  3. 将函数sharedDataStorage()导出到

Code of DataStorage.js

const SQLite = require('react-native-sqlite-storage');

const _dataStorage = null;

export class DataStorage {

    constructor(autoCheckMigration = true, lang = 'en') {
        console.log("DataStorage CTOR called");

        if(_dataStorage !== null) {
            throw 'There is already an instance of DataStorage alive';
        }

        // store this instance in a global variable
        _dataStorage = this;

        this.db = SQLite.openDatabase('myapp.db', '1.0', 'Myapps Database', 5 * 1024 * 1024, this.openCB, this.errorCB);

        if (autoCheckMigration) {
            this.checkDatabaseMigration(lang);
        }
    }

    many_other_convenience_methods_here(...) {}
}

export function sharedDataStorage() {
    return _dataStorage;
}

Applications root component:

在应用程序根组件中,我创建了调用其构造函数的数据库实例.

export default class Application extends React.Component {

    constructor(props) {
        super(props);

        this.setupDatabase();
    }

    render() {
        return (
            <Provider store={store}>
                    <ApplicationContainer />
          </Provider>
        );
    }

    setupDatabase() {
        this.setState( {dataStorage: new DataStorage()} );
    }
}

Some action_...js:

所有其他组件和操作文件现在都可以通过以下方式访问此数据存储类:

import { sharedDataStorage } from '../data/dataStorage';

...

async function persistContacts(contacts) {
    const dataStorage = sharedDataStorage();

    contacts.forEach( (contact) => {
        dataStorage.persistContact(contact);
    });
}

虽然我不确定是否有更好的方法在react native中共享数据库连接,但这种方法工作得很好.

还有哪些其他可能性?

推荐答案

我这样解决:

database.js

'use strict';
import React from 'react';
import SQLite from 'react-native-sqlite-storage';


var database_name = "dbname.db";
var database_version = "1.0";
var database_displayname = "db";
var database_size = 200000;

let conn = SQLite.openDatabase(database_name, database_version, database_displayname, database_size, openDBHandler, errorDBHandler);

class Database  {
    getConnection() {
        return conn;
    }
}

module.exports = new Database();

接下来,在组件中,您可以通过以下方式获得数据库连接:

var connection = Database.getConnection();

React-native相关问答推荐

PubNubReact无法工作,因为它已被废弃

使用 React Native 下载数据文件以供离线使用

无法在 React Native iOS 模拟器中按 URI 显示图像

在 React Native Paper 中更改 TextInput 的文本 colored颜色

为什么会出现此错误:Invariant Violation: Cannot update during an existing state transition

混合 JavaScript 移动开发 - Apache Cordova vs Capacitor with Ionic vs NativeScript vs React Native

由于依赖关系,在 run-android 上构建失败

如何以编程方式在 react-native 中截屏

如何在 React Native 中获取 TextInput 相对于其父级或屏幕的光标位置

react-native:如何在离线模式下在模拟器上运行应用程序?

React Native 有全局作用scope域吗?如果没有,我该如何模仿它?

使用像 React Navigation 这样的基于 JS 的导航解决方案优缺点?

如何判断 React Native 中的 AsyncStorage 中是否存在密钥? getItem() 总是返回一个promise对象

React Native Remote Debugger 在 Chrome 中显示缓存的包

React Native + Jest EMFILE:too many open files error

大型列表的 React-Native FlatList 性能问题

使用 React Native 一次启动多个 Animated.timing

React Native 模块中的依赖注入

如何从react-native应用程序打开外部应用程序?

React Native:无法解析模块 fs