Skip to content Skip to sidebar Skip to footer

React Parent Passing Props To A Child Causes Infinite Loops

What I'm trying to achieve: I want the user to be able to place red dots on a picture rendered in a canvas. That's it. What's happening? Every time I add said dots (CanvasComponent

Solution 1:

the call to the componentWillReceiveProps changes the props, thereby calling itself. A hack around this would be to compare if the current width and height isn't the same as the next.

componentWillReceiveProps(nextProps) {
 console.log('imageProps')
 const reader = new FileReader();
 reader.onload = async e => {
    await this.setState({image: e.target.result});
    const image = document.getElementById('image');
    const {naturalHeight, naturalWidth} = image;
    if ((nextProps.width !== this.props.width) ||(nextProps.height !== this.props.height) ) {
    nextProps.setDimensions(naturalWidth, naturalHeight);
    }
};
    reader.readAsDataURL(nextProps.image);
}

componentWillReceiveProps has been deprecated you can use the alternative

static getDerivedStateFromProps(nextProps, prevState) {
  // Called after a component is instantiated or before it receives new props.
  // Return an object to update state in response to prop changes.
  // Return null to indicate no change to state.
}

You can refer to this RFC to understand more about why this change was made.


Post a Comment for "React Parent Passing Props To A Child Causes Infinite Loops"