使用object.assign更新reducer中的嵌套数组

时间:2017-05-25 12:15:45

标签: reactjs

我有一个更新我的achievements数组中的项目的开关案例,我如何为DELETE_ACHIEVEMENT提供类似的从数组中删除文本的开关案例?

case ADD_ACHIEVEMENT:
  return state.map(item => {
      if (item.id === action.id) {
          return Object.assign({}, item, {
            achievements: [
            ...item.achievements,
            action.text,
            ]
          });
      }

    return item;
});

case REMOVE_ACHIEVEMENT:
  return state.map(item => {
      if (item.id === action.id) {
          return Object.assign({}, item, {
          // check text is in array and delete?
            achievements: [
            ...item.achievements,
            action.text,
            ]
          });
      }

    return item;
});

1 个答案:

答案 0 :(得分:0)

你可以使用Array.prototype.filter()来检查当前的成就并返回与action.text不同的元素:

case REMOVE_ACHIEVEMENT:
      return state.map(item => {
          if (item.id === action.id) {
              return Object.assign({}, item, {
                achievements: [
                ...item.achievements.filter(achievement => achievement !== action.text)
                ]
              });
          }

        return item;
    });