我正在使用PouchDB将我的远程数据库与我的localdb同步,下面的代码放在componentDidMount中
const that = this
var localDB = new PouchDB('localdb')
var remoteDB = new PouchDB('http://192.168.1.106:5984/remotedb')
localDB.sync(remoteDB, {
live: true,
retry: true
}).on('change', function (change) {
console.log('test')
that.setState({
items: [this.state.items, ...change.change.docs]
})
})
我不知道为什么它根本不做任何事情
那里有三个问题:
this
而不是that
。它几乎肯定会做一些事情:在控制台上写错误。 (而不是that
模式,只需使用箭头功能,这样你就可以使用它。)this.state.items
作为新状态的一部分),你必须使用setState的回调版本(more here) )。this.state.items
,而不是将该数组作为新数组中的第一个元素。 (我不知道你是否也想传播change.change.docs
。)修复所有三个:
localDB.sync(remoteDB, {
live: true,
retry: true
}).on('change', change => {
this.setState(({items}) => ({items: [...items, /*...*/change.change.docs]}));
})
(/*...*/
是:如果你真的想传播...
,可以在那里使用change.change.docs
,或者如果你不想传播,则使用that
。)
这使用箭头函数,因此您不需要setState
变量,并在参数列表中使用destructuring的items
的回调版本来获取items
状态成员并创建一个附加了change.change.docs
的新change
成员。
我们也可以在localDB.sync(remoteDB, {
live: true,
retry: true
}).on('change', ({change: {docs}}) => {
this.setState(({items}) => ({items: [...items, /*...*/docs]}));
})
回调的参数列表中使用destructuring:
qazxswpoi