【问题标题】:Repeatedly calling setState inside componentWillUpdate or componentDidUpdate?在 componentWillUpdate 或 componentDidUpdate 中反复调用 setState?
【发布时间】:2019-04-24 14:10:17
【问题描述】:

我正在尝试找出作为道具传入的 React 组件中背景图像的方向。

我首先创建一个 Image 对象并将其 src 设置为新的 Image:

  getImage() {
    const src = this.props.url;
    const image = new Image();
    image.src = src;

    this.setState({
      height: image.height,
      width: image.width
    });
  }

用高度和宽度更新状态后,我尝试在componentDidUpdate() 内部调用getOrientation()

  getOrientation() {
    const { height, width } = this.state;
    if (height > width) {
      this.setState({ orientation: "portrait" });
    } else {
      this.setState({ orientation: "landscape" });
    }
  }

然后我得到以下错误:

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.

有什么想法吗?

Link to Sandbox

【问题讨论】:

标签: javascript reactjs image orientation setstate


【解决方案1】:

你需要像这样包含prevProps

componentDidUpdate(prevProps, prevState) {
  ...
}

更多信息请见here

【讨论】:

  • 我已经有了?检查 Sandbox 中的 componentDidUpdate() 方法
  • 不,您的沙盒有:componentDidUpdate(prevState)。注意只有一个参数而不是两个:)
猜你喜欢
  • 1970-01-01
  • 2021-04-20
  • 2023-04-07
  • 2023-03-26
  • 2023-01-31
  • 2016-10-19
  • 1970-01-01
  • 2020-10-22
  • 2015-08-12
相关资源
最近更新 更多