【问题标题】:Update value in object in nested array in React Firestore更新 React Firestore 中嵌套数组中对象的值
【发布时间】:2019-05-28 16:17:36
【问题描述】:

我需要在 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})
        })
      }
    }

【问题讨论】:

  • 如果你使用 redux 作为你的状态管理器,你的状态应该是不可变的,我觉得它第一次没有抱怨很奇怪。您是否尝试过通过 reducer 更新数据?
  • 我尝试在 reducer 之前以异步操作(thunk)更新 firestorm 数据库中一个对象的值。我从数据库动态呈现给 DOM 的每个“评论”数据都在数组中的对象内部,

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


【解决方案1】:

我的朋友帮我解决了这个问题,现在我在 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...

【讨论】:

    猜你喜欢
    • 2019-11-02
    • 2021-04-14
    • 2019-10-10
    • 2020-12-27
    • 2021-12-15
    • 2019-08-03
    • 2023-01-23
    • 2019-02-13
    • 2022-09-27
    相关资源
    最近更新 更多