[英]Update value in object in nested array in React Firestore
我需要在 Firebase 數組中的特定索引處更新對象中的值字段
我試圖用所有對象抓取getState()
數組;
然后獲取我需要的對象索引;
然后為對象分配新值,在本例中為內容;
然后將整個數組( comments
)重寫為 newArray ( actualComments
),如下所示。
這是我想要的,但只是第一次。 如果我再次嘗試這樣做,我會收到錯誤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 中特定索引處的對象更新起作用了! 這是代碼,干杯
/////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...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.