问题描述
我需要更新对象的值字段,该对象位于Firebase数组中特定索引处
I need to update value field in object at specific index which is in array in Firebase
我试图通过 getState()
数组获取所有对象;
然后获取我需要的对象索引;
然后为对象分配新值,在这种情况下为内容;
然后将整个数组( comments
)重写为newArray( actualComments
),如下所示.
I tried to grab through getState()
array with all objects;
then get object index which I need;
then assign new value to object, in this case content;
then rewrite whole array (comments
) to newArray (actualComments
) as you can see below.
这是我想要的,但是这是第一次.如果再次尝试执行此操作,则会收到错误 TypeError:内容"为只读
.
And this works how I want, but only for the first time. If I try to do it again, I get error TypeError: "content" is read-only
.
export const editComment = (comment) => {
return (dispatch, getState, { getFirebase, getFirestore }) => {
const firestore = getFirestore();
let actualComments = getState().firestore.data.topics[comment.topicId].comments;
let numberArray = actualComments.findIndex(e => {return e.id === comment.commentId});
actualComments[numberArray].content = comment.editContent;
firestore.collection('topics').doc(comment.topicId).update({
comments: actualComments
}).then(() => {
dispatch({ type: 'EDIT_COMMENT' })
}).catch((error) => {
dispatch({ type: 'EDIT_COMMENT_ERROR', error})
})
}
}
推荐答案
我的朋友帮了我这个忙,现在我在Array中specifix索引的对象中的更新起作用了!这是代码,欢呼声
My friend helped me with this, and now my updates in object at specifix index in Array works! Here is code, cheers
/////Grab through reference all comments Array in firestore
let actualComments = getState().firestore.data.topics[comment.topicId].comments;
////make container for array
let updatedComments = [];
//// copy array from reference to empty updatedComments array
actualComments.forEach(comment => {
updatedComments.push({
content: comment.content,
createdAt: comment.createdAt,
editDate: comment.editDate,
edited: comment.edited,
id: comment.id,
idTopic: comment.idTopic,
name: comment.name,
nameId: comment.nameId
})
})
//// grab index which i want to update
let numberArray = actualComments.findIndex(e => {return e.id === comment.commentId});
//// update in specific index array
updatedComments[numberArray].content = comment.editContent;
updatedComments[numberArray].editDate = new Date();
updatedComments[numberArray].edited = true;
//// replace updated array in firestore
firestore.collection('topics').doc(comment.topicId).update({
comments: updatedComments
}).then...
这篇关于在React Firestore中更新嵌套数组中对象的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!