【问题标题】:repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState。 React 限制嵌套更新的数量以防止无限循环
【发布时间】:2021-04-20 03:16:21
【问题描述】:
componentDidUpdate(prevProps, prevState) {
const { data } = this.state;

if (prevState.data.date !== data.date) {
  const startDate = new Date(data.date.startDate);
  const endDate = new Date(data.date.endDate);
  const countDuration = new Date(endDate - startDate).getDate();
  this.setState({
    data: {
      ...this.state.data,
      duration: countDuration,
    },
  });
}

if (prevState.data.duration !== data.duration) {
  const startDate = new Date(data.date.startDate);
  const endDate = new Date(
    startDate.setDate(startDate.getDate() + +data.duration - 1)
  );
  this.setState({
    ...this.state,
    data: {
      ...this.state.data,
      date: {
        ...this.state.data.date,
        endDate: endDate,
      },
    },
  });
}

}

但这给了我错误,说超出了最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制了嵌套更新的数量以防止无限循环。

【问题讨论】:

  • 在 componentDidUpdate 中设置 setState 是非常危险的,而且我很确定这两个“if”条件之一始终为真,这会导致状态更新循环
  • 显然其中一个条件总是返回 true,每次重新渲染都会触发 setState。您必须打印出这些值并开始缩小问题范围,可能是您更新嵌套状态值的方式
  • 我怀疑 prevState.data.date !== data.date 总是返回 true 并且总是会被执行。这可能是因为您正在尝试比较两个具有 Date 类型属性的对象

标签: javascript reactjs


【解决方案1】:

您似乎在错误的位置更改了 data.date 和 data.duration 属性。结果,条件prevState.data.date !== data.dateprevState.data.duration !== data.duration 永远不会评估为true,因此每次都会发生setState 调用,从而导致无限循环

【讨论】:

    猜你喜欢
    • 2023-01-31
    • 2020-05-20
    • 2020-09-06
    • 2021-12-22
    • 2019-04-24
    • 1970-01-01
    • 2020-08-09
    • 2016-10-22
    • 2019-11-26
    相关资源
    最近更新 更多