我怀疑这也可能是一个正常的React问题,然而我正在构建一个react原生应用程序,并且对所有这些都是相当陌生的,所以希望我只是没有掌握一个概念。
在我的Home.js (我的主屏幕组件)中,我在我的应用程序中执行一个replicate.from,它将数据从我的couchDB服务器拉到我的应用程序中(单向同步)并创建一个索引。该代码如下所示
this.remoteDB = new PouchDB("http://localhost:5984/cs-test");
this.localDB = new PouchDB("cs-test", { adapter: "asyncstorage" });
this.localDB.replicate
.from(this.remoteDB, {
live: true,
retry: true
})
.then(function(localDb) {
localDb
.createIndex({
index: {
fields: ["type"],
name: "type"
}
})
.catch(function(err) {
console.log(err);
});
});然后,我(只是为了确保它正常工作)使用我的索引查询并将数据转储到控制台。
this.localDB
.find({
selector: {
type: { $eq: "sessions" }
}
})
.then(
function(result) {
console.log("HOME result");
console.log(result);
}.bind(this)
)
.catch(function(error) {
console.error(error);
});这个可以完美地工作。
我的问题是,在Home.js的render函数中,我包含了3个组件,它们都将使用localDB数据。我的假设是PouchDB的数据是应用程序范围的,但似乎只有在Home.js中才能访问this.localDB (这在我输入它时是有意义的,因为它是'this')。
您知道如何访问子组件中的pouchDB数据吗?
发布于 2018-08-15 05:08:31
如果您需要从不同的组件访问您的localDB,我建议将所有与DB相关的东西(getDoc、saveDoc、pullDocs等)移到一个模块中,然后在需要的地方导入它。如下所示:
// pdb.js
import PouchDB from 'pouchdb-react-native';
const localDB = new PouchDB(localDBname, {adapter: 'asyncstorage'});
const PDB = {};
PDB.getDoc = (docID)=> {
return new Promise((resolve, reject)=> {
localDB.get(docID)
.then((result)=> {return resolve(result)})
.catch((err)=> {
if (err.status === 404) {
// console.log(' ???????????? getDoc not found: ', docID)
return resolve(null)
} else {
// console.log('[!!!!======>!!!!!!] getDoc err: ', err)
return reject(err)
}
})
})
}
PDB.saveDoc = (doc)=> {
...do stuff
}
module.exports = PDB;然后导入并在任何需要它的组件中使用它:
//mycomponent.js
import PDB from './pdb';
...
class MyComponent extends React.Component {
componentDidMount() {
PDB.getDoc(docID)
.then((doc)=> {
this.setState({name: doc.name})
})
}
render() {
return (
...https://stackoverflow.com/questions/51828242
复制相似问题