Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

reactjs - ComponentDidUpdate() keeps looping

class RatingsComponent extends Component{
    componentDidMount(){
        console.log("inside component did MOUNT")
        this.props.fetchReviews()
    }

    shouldComponentUpdate(nextProps){
        console.log("inside SHOULD update")
        return (nextProps.reviews !== this.props.reviews);
    }
    componentDidUpdate(prevProps){
        if(prevProps.reviews !== this.props.reviews)
        {  console.log("inside component did update")
           //    this.props.fetchReviews()  //commented due to infinite looping and hitting API
        }
    }

    render(){
      console.log("inside render");
      return null;
    }
}

fetchReviews() is an action that hits the API through saga and updates reviews state through reducer. Code absolutely works fine with componentDidMount(). I was curious and wanted to handle change in data if we are on the same page. I tried adding actionListener but there was no change. I added componentDidUpdate() as above. It worked but API is being hit infinite times. But the value of prevProps.reviews and this.props.reviews are same. I can't understand why this is happening. Any help is appreciated. P.s: Can't show the code inside render() due to official concerns, simply returning null also causes same issue.

question from:https://stackoverflow.com/questions/66061164/componentdidupdate-keeps-looping

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The issue is in the condition: you are not checking if the list of the reviews contains the same IDs, but you are just saying that if reviews!==previous fire fetch. This means that every time you retrieve a new array of reviews, even if the content is equal, the fetch request is fired again.

The loop is:

UpdateComponent->ComponentUpdated->ConditionIsTrue->FireFetch->UpdateComponent

And condition is always true since you are controlling two arrays in different memory address

Try using a statement like this and see if it solve your issue:

//diff is an array that will contain all the differences between this.props and previousProps
let diff= this.props.reviews.filter(review=> !previousProps.reviews.includes(review));

//if there are differences, call fetch
if(diff.lenght>0){
  this.props.fetchReviews()
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...