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实例,我执行了以下操作:
- 构建数据存储类
- 创建仅驻留在数据存储中的全局变量.js
- 将函数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中共享数据库连接,但这种方法工作得很好.
还有哪些其他可能性?