我将项目列表存储为firestore集合中的文档。当新项目添加到列表中时,它们将存储在组件状态中的单独变量中,但与已保存到firestore的项目数组合并。
只有在调用保存它们的手动调用时,才会将文档添加到firestore集合中。调用save调用时调用的逻辑如下:
if (this.state.unsavedNoteItems.length){
let items = this.state.unsavedNoteItems.map(item => item) //make a local copy of unsaved items
this.setState({unsavedNoteItems:[]}) //clear unsaved items array in component state
items.map(item => {
docRef.collection('items').add(item)
.then(doc => {
console.log("item saved: ", doc.id)
//if item was added successfully, merge it into note Items
this.setState((pState) => {noteItems: [...pState.noteItems,item]})
console.log('state was set', item)
})
.catch(error => {
console.log("Error: ", error)
//if item add failed, put is back in unsavedNoteItems list
this.setState((pState) => {unsavedNoteItems: [...pState.unsavedNoteItems,item]})
})
})
}
在添加项目后的解析程序中,this.setState
不会更新UI,即使更改仍然存在。
我已经通过创建查询快照解决了这个问题,但想要了解为什么setState调用不会更新UI。有什么想法吗?
答案 0 :(得分:1)
(pState) => {noteItems: [...pState.noteItems,item]}
此处{ }
不是对象文字,而是块语句。
const iReturnUndefined = value => {a: value}
const iReturnObject = value => ({a: value})
console.log(iReturnUndefined('a'))
console.log(iReturnObject('a'))
您需要用()
包装它以使其成为对象初始化表达式
if (this.state.unsavedNoteItems.length){
let items = this.state.unsavedNoteItems.map(item => item) //make a local copy of unsaved items
this.setState({unsavedNoteItems:[]}) //clear unsaved items array in component state
items.map(item => {
docRef.collection('items').add(item)
.then(doc => {
console.log("item saved: ", doc.id)
// NB! 1
this.setState(pState => ({noteItems: [...pState.noteItems,item]}))
console.log('state was set', item)
})
.catch(error => {
console.log("Error: ", error)
// NB! 2
this.setState(pState => ({unsavedNoteItems: [...pState.unsavedNoteItems,item]}))
})
})
}