1

我需要放一张图片,然后上传到服务器并更新界面。我有一个问题,生命周期方法 componentDidUpdate 开始无限更新,在我指示将 this.state 与 prevState 进行比较的条件下。(PrevState 未定义,我不明白为什么)。

我把我的代码放在沙箱里,希望能清楚。 https://codesandbox.io/s/headless-smoke-4xxi2

4

3 回答 3

2

为什么:这似乎是一个参考/可变内存地址问题。

当您存储时,itemsList您正在创建一个新的引用,因为您从 api 接收到一个非原始值。当涉及到非原始值时,JS 总是使用引用进行操作。因此,您if (this.state.itemsList !== prevState.itemsList)将始终返回true,因为itemsList它是一个非原始数据集的数组,这意味着 JS 不检查它的值,而只检查引用。

在这种情况下,我看到两个解决方案 atm:

  1. 如果值相同,则阻止更新状态

或者

  1. 在此语句中使用适当的检查器函数检查值if (this.state.itemsList !== prevState.itemsList)

希望我能解释一下。干杯!

于 2019-07-11T11:23:40.280 回答
0

您没有使用正确的参数。请参阅 componentDidUpdateprevProps作为第一个参数和prevState第二个参数。

在此处输入图像描述

试试这个

componentDidUpdate(prevProps, prevState)
于 2019-07-11T11:25:22.470 回答
0

prevState 是 componentDidUpdate 的第二个参数。尝试 -

componentDidUpdate(prevProp, prevState) {
    console.log(this.state.itemsList, prevState.itemsList);
    if (this.state.itemsList !== prevState.itemsList) {
      // if you remove the comment from this method, then an infinite update will begin
      //
       this.updateItemList();
    }
  }
于 2019-07-11T11:28:45.527 回答