简体   繁体   中英

Repeatedly calling setState inside componentWillUpdate or componentDidUpdate?

I'm trying to figure out the orientation of background-images in a React component that are passed in as props.

I start off by creating an Image object and setting its src to the new Image:

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

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

After I've updated the state with the heights and widths, I try calling getOrientation() inside of componentDidUpdate() :

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

I then get the following error:

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

Any ideas what's going on here?

Link to Sandbox

You need to include prevProps like so:

componentDidUpdate(prevProps, prevState) {
  ...
}

For more see here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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