setState无法在不覆盖的情况下扩展到嵌套数组中-不变性,做出反应

时间:2018-09-20 20:50:42

标签: reactjs ecmascript-6 setstate spread-syntax

鉴于我有以下x3复选框输入元素:

<input name="notifications.updatesCategoryNotifications.email_newsletter"" ... />
<input name="notifications.updatesCategoryNotifications.shopping" ... />
<input name="misc.updatesCategoryNotifications.profile" ... />

并希望从其name属性构造一个数据结构:

handleCheckboxChange(event) {
    const { target } = event;
    const type = target.name.split('.')[0]; // notifications
    const parent = target.name.split('.')[1]; // updatesCategoryNotifications
    const child = target.name.split('.')[2]; // email_newsletter

    // change-up the checked value in relevant object
    const activeArray = [...this.state[parent]];
    const activeArrayIdx = activeArray.map(item => item.name === child).indexOf(true);
    activeArray[activeArrayIdx].value = target.checked;

    // redo state and group things to send
    this.setState({
      dirtyData: {
        ...this.state.dirtyData,
        [type]: [
          activeArray[activeArrayIdx]
        ],
      },
    });
  }

预期结果:(this.state.dirtyData)

{
  "misc": [
    {
      "name": "profile",
    }
  ],
  "notifications": [
    {
      "name": "email_newsletter",
    },
    {
      "name": "shopping",
    }
  ]
}

实际结果:(this.state.dirtyData)

{
  "misc": [
    {
      "name": "profile",
    }
  ],
  "notifications": [
    {
      "name": "email_newsletter",
    },
  ]
}

当前,只有一次又一次地将一个对象发送到[type]属性数组。我需要将其添加到自己的[type]中。认为我只是错过了使用传播算子的技巧吗?

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

在这里做个猜测,因为您已经在activeArray中修改了值,所以您可以散布它:

// redo state and group things to send
this.setState({
  dirtyData: {
    ...this.state.dirtyData,
    [type]: [
      ...activeArray
    ],
  },
});

或仅分配它,例如[type]: activeArray,