是否可以在我的React Native应用程序中预加载/预填充数据库,然后在第一次运行时,只需执行同步?在应用程序发布之前,我已经拥有了大部分(如果不是全部)数据库信息,如果它只是在运行应用程序时必须快速同步,那就太棒了。有什么想法我会怎么做呢?
我发现了这个 - https://pouchdb.com/2016/04/28/prebuilt-databases-with-pouchdb.html但它没有提到React Native
使用:
谢谢你的任何指示。
更新这是我用来尝试加载转储文件的代码。此代码存在于/screens/Home.js中。转储文件位于/client/dbfile/database.txt中
var db = new PouchDB("cs1");
db.get("_local/initial_load_complete")
.catch(function(err) {
console.log("loading dumpfile");
if (err.status !== 404) {
// 404 means not found
throw err;
}
db.load("/client/dbfile/database.txt").then(function() {
return db.put({ _id: "_local/initial_load_complete" });
});
})
.then(function() {
// at this point, we are sure that
// initial replication is complete
console.log("loading is complete!");
return db.allDocs({ include_docs: true });
})
.then(
function(res) {
// display all docs for debugging purposes (empty)
console.log(res);
});
this.localDB = db;
当这个运行我的控制台显示这个 - 显示已添加0行。
Object {
"offset": 0,
"rows": Array [],
"total_rows": 0,
}
Possible Unhandled Promise Rejection (id: 0):
Object {
"message": undefined,
"name": "unknown",
"status": 0,
}
在我的项目中,我有几个我用app分发的db文档(翻译JSON就是一个很好的例子)。所以在app init我只是尝试从db读取翻译文档,如果没有 - 我从js模块导入内容并存储在db中。然后翻译只是从服务器复制到本地数据库。
//transmob.js
const transMobFile = {
//content goes here
);
module.exports = transMobFile
//dbInit.js
import transMobFile from 'data/transMob';
..
PDB.getDoc('TransMob')
.then((doc)=> {
if (!doc) {
global.locales = transMobFile.localesMob; // locales
global.translations = transMobFile.langMob; // translations
return PDB.saveDoc('TransMob', transMobFile)
}
})
您可以使用react-native-fs从/ android / app / src / main / assets加载文件。只需将文件放入assets文件夹并使用RNFS.readFileAssets读取即可。
import PouchDB from 'pouchdb-core';
PouchDB
.plugin(require('pouchdb-find'))
.plugin(require('pouchdb-load'));
import RNFS from 'react-native-fs';
const localDB = new PouchDB("cs1", {adapter: 'asyncstorage'});
localDB.get("_local/initial_load_complete")
.catch(function(err) {
console.log("loading dumpfile");
if (err.status !== 404) {
// 404 means not found
throw err;
}
RNFS.readFileAssets('yourdb.txt', 'utf8')
.then((contents) => {
localDB.load(contents).then(function() {
return localDB.put({ _id: "_local/initial_load_complete" });
}).then(function() {
// at this point, we are sure that
// initial replication is complete
console.log("loading is complete!");
return localDB.allDocs({ include_docs: true }).then(
function(res) {
// display all docs for debugging purposes (empty)
console.log(res);
});
}, function(err) {
console.log(err);
});
})
})
您需要重建项目,重新加载是不够的。当我尝试加载30MB文件时,我的项目崩溃了,所以我可能会将它拆分成几个较小的文件。查看https://github.com/pouchdb-community/pouchdb-load,看看如果需要,它是如何工作的。
我发现db.load()
模块中的pouchdb-load函数需要一个URL。我将它指向设备文件系统上的文件路径。我将我的database.txt文件放在我的服务器上,将其更改为使用url并且它有效。
在我看来这并不理想,因为如果他们安装应用程序并且无线速度慢,它仍然必须从服务器中提取文件。当应用程序第一次打开时,它仍然比执行完全复制快得多。