将对象替换为状态 React 中的另一个对象

Replacing object for another in state React

我有一组对象。我找到了我需要替换的对象,但无法在状态下替换它。原始对象保持不变,我想要替换它的对象被添加到数组的末尾。我正在使用 React 钩子。谢谢

case types.ADD_USERNAME: 
  let task = action.payload
  let assignedTask = state.tasks.find(el => el.id === task.id)
  let index = state.tasks.indexOf(assignedTask)

  return {
    ...state, 
    tasks: [
      ...state.tasks,
      assignedTask = {
        ...assignedTask,
        user: task.user.name
      }
    ]
} 

您可以使用地图而不是通过索引查找元素来更新状态,我认为这是一种更简洁的方法

case types.ADD_USERNAME: 
  let task = action.payload;

  return {
    ...state, 
    tasks: state.tasks.map(el => {
        if(el.id == task.id) {
           return { ...el, user: task.user.name} 
        }
        return el;
    });
} 

但是如果你想通过索引和查找元素的方法,你需要对任务数组进行切片并更新特定的索引元素

case types.ADD_USERNAME: 
  let task = action.payload
  let index= state.tasks.findIndex(el => el.id === task.id);

  return {
    ...state, 
    tasks: [
      ...state.tasks.slice(0, index - 1),
      {
        ...state.tasks[index],
        user: task.user.name
      }
      ...state.tasks.slice(index + 1)
    ]
} 

您可以通过使用地图并通过 id 或任何其他唯一标识符匹配您的对象来实现此目的:

case types.ADD_USERNAME:
  let task = action.payload;

  return {
    ...state,
    tasks: state.tasks.map(t => {
      if (t.id === task.id) {
        return {
          ...t,
          user: task.user.name
        };
      }
      return t;
    })
  };