繁体   English   中英

在componentWillUpdate或componentDidUpdate中反复调用setState?

[英]Repeatedly calling setState inside componentWillUpdate or componentDidUpdate?

我试图弄清楚作为道具传递的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() componentDidUpdate()

  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.

有什么想法在这里发生了什么?

链接到沙盒

您需要包含prevProps如下所示:

componentDidUpdate(prevProps, prevState) {
  ...
}

有关详情,请参阅此处

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM