javascript - 使用 reducer 更新状态内的特定值

标签 javascript arrays reactjs object redux

我正在尝试更新状态内对象数组内的特定值(在本例中为列表内的注释)。在本例中,注释位于 msgs 键内。

 const list = [{
    id: 1,
    text: "list text",
    msgs: [{
      id: 1,
      comment: "comment",
      commentID: "ab37afa-c17-e4f-f103-4715b72f14ec"
    }]
  },
  {
    id: 2,
    text: "list text 2",
    msgs: [{
      id: 2,
      comment: "comment2", <--- trying to update this value
      commentID: "ab37afa-c17-e4f-f103-4715b72f14ec-2"
    },
    {
      id: 2,
      comment: "comment3",
      commentID: "ab37afa-c11323127-e4f-f103-4715b72f14ec-2"
    }]
  }
];

我目前正在尝试使用 reducer :

case "EDIT_COMMENT":
      temp = state.filter((list => list.id === parseInt(action.comment.id)))  //getting the list that I want
      const msgs = [].concat(...temp).map(x=> ({
        id: x.id,
        comment : x.comment,
        commentID : x.commentID
        })) // trying to get the messages inside the state


     // I honestly don't know what to put here
      return msgs.map( msg => {
        if(msg.commentID === action.payload.commentID){
          return {...}
        }
      }        
        )

我无法得到答案/解决方案来更新我想要的 reducer 数据,如果有人可以帮助我解决这个问题,我将不胜感激。 预先感谢,祝周末愉快:)

最佳答案

如果我理解正确,您想要更新 state 任何给定项目上的任何嵌套 msg 注释(我假设它与所示列表的形式匹配)在你的问题中) - 在这种情况下,一个简单的解决方案可能如下:

case "EDIT_COMMENT": {

  return state.map(messageItem => {

    return {
      // Clone input messageItem
      ...messageItem,

      // Overwrite msgs field with new msgs array
      msgs : messageItem.msgs.map(commentItem => {

        if(commentItem.commentID === action.payload.commentID) {
          return {
            // Clone input commentItem
            ...commentItem,

            // Overwrite fields that this action should update,
            // on commentItem matching by comment id ie, "comment"
            // from action payload
            comment : action.payload.comment
          }      
        }
        else {
          // If message does not match actions comment id, return
          // a clone of commentItem to mapped list
          return {...commentItem}
        }
      })
    }    
  });
}

这里的假设是:

  • state 是一个与问题中所示的 list 形式匹配的数组
  • 操作负载中的 commentId 对于 msg 子数组中的评论来说是唯一的。
  • 操作负载中的comment字段包含新的评论字符串,用于更新现有的匹配评论

希望有帮助!

关于javascript - 使用 reducer 更新状态内的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59330350/

相关文章:

javascript - 清空下拉选择office-ui-fabric react组件

javascript - Chrome 应用可以注册协议(protocol)处理程序吗?

.net - 通过 COM 可见 DLL 从 VB6 调用 .NET 方法

css - 使用 css 后代选择器 react 主题

javascript - 如何正确拆分字符串数组,这是另一个问题吗?

javascript - 从数组中的 SQL 捕获 PHP 变量并输出到 JavaScript 变量

javascript - 使 JSON 中的数据成为 Dynamodb 中自己的属性?

javascript - 我应该在原型(prototype)中添加或删除该类之前检查该类吗?

javascript - 找不到模块 : Error: Can't resolve '@angular/material' when building dist for npm package

Javascript document.write() 指向另一个页面