在componentWillUpdate或componentDidUpdate内部重复调用setState吗?

A7D*_*7DC 5 javascript image orientation setstate reactjs

我试图弄清楚作为组件传递的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
    });
  }
Run Code Online (Sandbox Code Playgroud)

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

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

然后,我得到以下错误:

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

链接到沙盒

Col*_*rdo 6

您需要prevProps像这样包含:

componentDidUpdate(prevProps, prevState) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参见此处