更新嵌套对象,同时保持其余部分不变

时间:2019-03-04 08:39:41

标签: javascript reactjs redux

我从redux开始,我想对我的内容进行以下修改 状态:

从此:

state = {
  loaded: true,
  fetching false,
  byId: {
    "employeeID1": {
      id: "employeeID1",
      name: "Steve"
     },
    "employeeID2": {
      id: "employeeID2",
      name: "Susan"
     }
  }
}

对此:

{
  loaded: true,
  fetching false,
  byId: {
    "employeeID1": {
      id: "employeeID1",
      name: "Steve",
      data: data  // <---- add a new property

     },
    "employeeID2": {
      id: "employeeID2",
      name: "Susan"
     }
  }
}

const modifEmployee = {...state.byId["employeeID1"], data: data}将为我提供数据的修改后的员工。

但是,如何在保持其他人不变的情况下将修改后的员工添加到byId中?

1 个答案:

答案 0 :(得分:3)

您可以使用传播语法执行以下操作:

public class MessageListViewAdapter : BaseAdapter
{
    List<Model.Message> messages = new List<Model.Message>();
    Context context;

    public MessageListViewAdapter(Context context,List<Model.Message> messages)
    {
        this.context = context;
        this.messages = messages;
    }
    public void add(Model.Message message)
    {

        if (!messages.Contains(message))
        {
            this.messages.Add(message);
            NotifyDataSetChanged(); // to render the list we need to notify
        }         
    }
    public override int Count =>messages.Count;

    public override Java.Lang.Object GetItem(int position)
    {
        return null;
    }

    public override long GetItemId(int position)
    {
        return position;
    }

如果{ ...state, byId: { ...state.byId, employeeID1: { ...state.byId.employeeID1, data } } } 的值是从变量"employeeID1"提取的,则可以使用computed property names

employeeId