【问题标题】:why do I get the error X is not iterable when setting state with the spread operator?为什么在使用扩展运算符设置状态时出现错误 X 不可迭代?
【发布时间】:2021-06-25 09:51:58
【问题描述】:

我有两个按钮,单击它们会更新对象数组的状态。 videoList 是对象数组的状态,currentVideo 是用户当前正在观看的视频的状态。这些按钮在 currentVideo 的对象中将标志 id 设置为 true 或 false。在第一次单击时,一切都按预期工作,但是如果再次单击,我会收到错误:TypeError: videoList is not iterable。我该如何解决这个问题?

 const true = () => {
    setVideoList(
      ...videoList,
      (videoList[videoList.indexOf(currentVideo)].flag = true)
    );
    // setCurrentVideo(...currentVideo, (currentVideo.flag = true));
  };

  const false = () => {
    setVideoList(
      ...videoList,
      (videoList[videoList.indexOf(currentVideo)].flag = false)
    );
  };

 return (
    <div>
      <Button onClick={true}>
        True
      </Button>
      <Button onClick={false}>
        False
      </Button>
    </div>
  );
};

【问题讨论】:

    标签: javascript reactjs state setstate iterable


    【解决方案1】:

    您没有正确更新您的状态。展开后,需要再次将其转为数组。另一件事,如果您的下一个状态取决于旧状态,请传递这样的函数

     setVideoList(
         videoList => [...videoList, (videoList[videoList.indexOf(currentVideo)].flag = true) ]
      );
    

    【讨论】:

      猜你喜欢
      • 2018-05-17
      • 1970-01-01
      • 2018-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      相关资源
      最近更新 更多