首页 > 解决方案 > 如何使用扩展运算符在循环中设置状态()

问题描述

我正在尝试使用循环中的扩展运算符为嵌套对象中的多个字段设置新值,但它仅适用于最后一个字段。

我有一个数组“formFields”,其中包含我想要覆盖的值的字段名称。我使用 map() 将数组中的每个元素与状态中的字段进行比较,并将其值切换为“true”。但它仅更改数组中最后一个字段的值 - “评论”。

constructor() {
    super();
    this.state = {
        fields: {
            time: false,
            date: false,
            quantity: false,
            comment: false,
        },
    }
}

getFormFields() {
    const formFields = ["time", "quantity", "comment"];
    formFields.map(item => {
        this.setState({
            ...this.state.fields,
            [item]: true
        })
    });
}

我应该怎么做才能覆盖我想要的所有字段的值?

标签: reactjsecmascript-6

解决方案


由于您正在循环更改状态,并且您设置的每个状态都包含仅更改的原始项目,因此最新更改会覆盖前一个更改。相反,使用更改创建一个新的状态对象,然后 setState 对象一次:

getFormFields() {
  const formFields = ["time", "quantity", "comment"];
  this.setState(formFields.reduce((r, item) => ({
    ...r,
    [item]: true
  }), {}));
}

顺便说一句 - 如果您要设置的字段true始终相同,您可以手动创建对象并设置它:

getFormFields() {
  this.setState({
      time: true,
      quantity: true,
      comment: true,
  });
}

推荐阅读