为什么setState在React功能组件中不起作用

时间:2020-06-19 00:56:14

标签: javascript reactjs react-functional-component

const [bullyTypes, setBullyTypes] = React.useState([
  { value: "Exotic", isChecked: false },
  { value: "Pocket", isChecked: false },
  { value: "Classic", isChecked: false },
  { value: "Standard", isChecked: false },
  { value: "Extreme", isChecked: false },
  { value: "XL", isChecked: false },
]);

const handleBullyTypeChange = (event) => {
  let bullyTypesCopy = bullyTypes;
  bullyTypesCopy.forEach((bullyTypeCopy) => {
    if (bullyTypeCopy.value === event.target.value) {
      bullyTypeCopy.isChecked = event.target.checked;
    }
  });
  setBullyTypes(bullyTypesCopy); // not working

  setBullyTypes([
    { value: "Exotic", isChecked: true },
    { value: "Pocket", isChecked: false },
    { value: "Classic", isChecked: false },
    { value: "Standard", isChecked: false },
    { value: "Extreme", isChecked: false },
    { value: "XL", isChecked: false },
  ]); // this is working even though bullyTypesCopy variable has the same value with this array of objects.
};

当我将确切的数组作为参数传递给setBullyTypes时,它将起作用 但是当我传递包含数组的变量时,即使它们具有相同的值,它也将无法工作

请帮助我。谢谢

1 个答案:

答案 0 :(得分:2)

在事件处理程序bullyTypesCopy被引用复制的情况下,forEach并没有达到您的期望,它只是遍历数组项。我认为您需要做的是使用map,以便根据您的情况实际获得新的内容。这样setBullyTypes应该可以工作。

请尝试以下示例

const [bullyTypes, setBullyTypes] = React.useState([
  { value: "Exotic", isChecked: false },
  { value: "Pocket", isChecked: false },
  { value: "Classic", isChecked: false },
  { value: "Standard", isChecked: false },
  { value: "Extreme", isChecked: false },
  { value: "XL", isChecked: false },
]);

const handleBullyTypeChange = (event) => {
  let bullyTypesCopy = bullyTypes.map((bullyTypeCopy) => {
    if (bullyTypeCopy.value === event.target.value) {
      return { ...bullyTypeCopy, isChecked: !event.target.checked };
    }

    return { ...bullyTypeCopy };
  });

  setBullyTypes(bullyTypesCopy); // not working // this should work now

  setBullyTypes([
    { value: "Exotic", isChecked: true },
    { value: "Pocket", isChecked: false },
    { value: "Classic", isChecked: false },
    { value: "Standard", isChecked: false },
    { value: "Extreme", isChecked: false },
    { value: "XL", isChecked: false },
  ]); // this is working even though bullyTypesCopy variable has the same value with this array of objects.
};