向对象添加新属性

时间:2019-12-14 10:37:45

标签: javascript reactjs

我正在尝试向要标记为完成的练习中添加新属性,但我无法获得正确的形状。

这是减速器:

case COMPLETE_EXERCISE:
      return {
        ...state,
        [action.payload.id]: {
          ...[action.payload.completedExercise],
          complete: true
        }
      };

我想将complete: true属性添加到completedExercise对象,并摆脱该0索引对象键,以使{{1 }}对象包含IdcompletedExercisesnamescreenName道具,但是我能想到的最接近的是将其放在旁边:

enter image description here

我当前的状态如下:

currentstate

并且我希望它看起来像:

enter image description here

1 个答案:

答案 0 :(得分:2)

请勿将action.payload.completedExercise包装在数组中

case COMPLETE_EXERCISE:
      return {
        ...state,
        [action.payload.id]: {
          ...action.payload.completedExercise,
          complete: true
        }
      };

示例:

const foo = { a: 1 };
const bar = {
  ...foo,
  b: 2
};

console.log(bar);