【问题标题】:how to add new value to json如何为json添加新值
【发布时间】:2020-01-28 17:04:48
【问题描述】:
pin = [
    {
        "id": 26,
        "comments": [
            {
                "id": 2,
                "username": "user",
                "description": "example",
                "pin": 26,
                "commenter": 1
            },
            {
                "id": 3,
                "username": "admin",
                "description": "example",
                "pin": 26,
                "commenter": 17
            }
        ],  
    }
]

用户会发布一条新评论,我希望它在 cmets 数组下添加新评论 我试过这样写,但其他值变成空白

   case ADD_COMMENT:
      return {
        ...state,
        pin: [...state.pin.commentstory, action.payload]
      };

如何向 cmets 数组添加新值?

【问题讨论】:

  • 我想你想要pin: [...state.pin, action.payment]

标签: javascript arrays json reactjs redux


【解决方案1】:

这会将action.payload 添加到您的pin 数组中:

case ADD_COMMENT:
  return {
     ...state,
     pin: [...state.pin, action.payload]
  }

要将项目添加到pin 数组中的comments 数组,您需要一种方法来确定pin 数组中的哪个 项目应该接收更新。

case ADD_COMMENT:
  // suggested payload structure
  const pinId = action.payload.pinId;
  const newComment = action.payload.comment;

  const newPins = state.pin.map(p => { 
     if (p.id !== pinId) { return p };
     return {...p, comments: [...p.comments, newComment]};
  });
  return {
    ...state,
    pin: newPins
  };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 2017-01-06
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 2022-01-15
    相关资源
    最近更新 更多