[英]react setState doesn't work with stream data?
我正在使用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]
})
})
我不知道為什么它什么都不做
那里存在三個問題:
您已經在change回調中使用了this
而不是that
。 幾乎可以肯定,它正在做一些事情:在控制台中寫一個錯誤。 (而不是that
模式,只需使用箭頭功能,就可以使用它。)
您違反了React的基本規則之一:如果要基於現有狀態設置狀態(您正在使用this.state.items
作為新狀態的一部分),則必須使用回調版本setState的( 這里有更多 )。
您幾乎肯定要散布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
,請使用...
change.change.docs
,請刪除它。)
它使用箭頭函數,因此您不需要that
變量,並使用setState
的回調版本以及在參數列表中進行銷毀的功能來獲取items
狀態成員,並創建一個附加了change.change.docs
的新items
成員。
我們也可以在change
回調的參數列表中使用解構:
localDB.sync(remoteDB, {
live: true,
retry: true
}).on('change', ({change: {docs}}) => {
this.setState(({items}) => ({items: [...items, /*...*/docs]}));
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.