簡體   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