在React Firestore中更新嵌套数组中对象的值

时间:2019-01-01 21:44:39

标签: javascript reactjs firebase redux google-cloud-firestore

我需要更新对象中位于Firebase数组中特定索引处的value字段

我试图通过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})
        })
      }
    }

1 个答案:

答案 0 :(得分:0)

我的朋友帮助了我,现在我在Array的specifix索引的对象中更新了!这是代码,欢呼声

    /////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...