react setState不能与流数据一起使用?

问题描述 投票:0回答:1

我正在使用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]
    })
})

我不知道为什么它根本不做任何事情

javascript reactjs pouchdb
1个回答
1
投票

那里有三个问题:

  1. 你在改变回调中使用了this而不是that。它几乎肯定会做一些事情:在控制台上写错误。 (而不是that模式,只需使用箭头功能,这样你就可以使用它。)
  2. 你违反了React的一个基本规则:如果你根据现有状态设置状态(你使用this.state.items作为新状态的一部分),你必须使用setState的回调版本(more here) )。
  3. 你几乎肯定想要传播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变量,并在参数列表中使用destructuringitems的回调版本来获取items状态成员并创建一个附加了change.change.docs的新change成员。

我们也可以在localDB.sync(remoteDB, { live: true, retry: true }).on('change', ({change: {docs}}) => { this.setState(({items}) => ({items: [...items, /*...*/docs]})); }) 回调的参数列表中使用destructuring:

qazxswpoi
© www.soinside.com 2019 - 2024. All rights reserved.