问题描述
我目前无法从Firebase Firestore的数组中删除项目。我可以在本地删除它,但刷新后会再次显示它。我知道我应该使用实际值。这是我的相关代码,这就是我的Firestore
const removeGoalHandler = async (goalId) => {
let goalToDel = {}
for(let i =0; i < courseGoals.length; i++){
if(courseGoals[i].id == goalId){
console.log(courseGoals[i])
goalToDel = courseGoals[i]
}
}
const removeGoal = await loansRef.doc(userId).update({
goals: firebase.firestore.FieldValue.arrayRemove(goalToDel)
})
setCourseGoals((currentGoals)=> {
return currentGoals.filter((goal)=> goal.id !== goalId)
})
setGoalCounter(goalCounter-1)
};
const addToFB = async (goalTitle,interestRate,years,paidOff,id) => {
//adding data to firebase,takes into account if doc exists already
if(id==undefined){
id = goalCounter
}
console.log('add to firebase')
const loadDoc = await loansRef.doc(userId).get()
.then((docSnapshot)=> {
if(docSnapshot.exists){
loansRef.doc(userId).onSnapshot((docu)=>{
console.log('num2: '+ (goalCounter+id).toString())
const updateLoansArr = loansRef.doc(userId).update({
goals: firebase.firestore.FieldValue.arrayUnion({
id: userId+(goalCounter+id).toString(),value: goalTitle,interest: interestRate,years: years,paidOff: paidOff
})
})
})
}
else{
console.log('num3: '+ (goalCounter+id).toString())
const addDoc = loansRef.doc(userId).set({
goals: firebase.firestore.FieldValue.arrayUnion({
id: userId+(goalCounter+id).toString(),paidOff: paidOff
})
})
}})
}
这是我实际添加贷款的代码;在这里,它调用addToFB()将其添加到Firebase哈哈
const addGoalHandler = (goalTitle,id) => {
console.log('add goal handler')
if(id==undefined){
id = 0
}
console.log('num1: '+ (goalCounter+id).toString())
//console.log(goalCounter)
setGoalCounter(goalCounter+1)
setCourseGoals((courseGoals) => [
...courseGoals,{
id: userId + (goalCounter+id).toString(),paidOff: paidOff
}
]);
//console.log(goalCounter)
addToFB(goalTitle,id)
setIsAddMode(false);
}
解决方法
您遇到的问题是arrayRemove()
使用严格相等来比较数组元素并确定要删除的元素,而不是像在代码中那样比较“ id”。不幸的是,这意味着每个对象都将被视为与其他每个对象(无论是不同的id还是相同的id)不同,无论它们如何相同({} === {} //false
),因此它找不到要删除的元素。 arrayRemove()
对于包含原始类型(数字,字符串等)的数组会更好。
就目前而言,最好的选择是获取现有文档,使用“ id”逻辑删除所需的元素并将其写回。像这样:
const removeGoalHandler = async (goalId) => {
const existingDoc = await loansRef.doc(userId).get();
const goals = existingDoc.data().goals.filter(goal => goal.id !== goalId);
await loansRef.doc(userId).update({ goals });
setCourseGoals(goals);
...
};