Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router - calling same method outside componentDidMount

Tags:

reactjs

I have a React application where pages are linked using React router. The user is provided with several links. Each link is handled through the router.

All of the corresponding pages have similar logic before render function, so I used a URL parameter, a single Route path, and the same target component. The URL parameter is supposed to be passed to the backend service.

Since the target component is the same and only distinguishing factor is the URL parameter, once the component is rendered for any of the links, the lifecycle methods like componentWillMount, componentDidMount do not execute again. So, even if I click on another link whatever is the state created by the first hit, same is used for other links. REST call is within componentDidMount. Am I missing something?

<Route path="/location/:locationType" component={MapSelectedLocation}/>

MapSelectedLocation is supposed to handle several locationType and invoke REST service based on that.

The expected result is to execute the same code for different locationType. How can I achieve this?

like image 882
Swapnil Avatar asked Jun 08 '26 04:06

Swapnil


1 Answers

You need to use componentDidUpdate lifecycle method to do the calculation or each props/state change. Put the check in this method and compare the prevProps and new props value. Also this method will not get called on initial rendering

Like this:

componentDidMount() {
  this.doCalculation();
}

componentDidUpdate(prevProps) {
  if(this.props.match.params.locationType != prevProps.match.params.locationType) {
    this.doCalculation()
  }
}

doCalculation() {
  // do the calculation here
}
like image 125
Mayank Shukla Avatar answered Jun 10 '26 20:06

Mayank Shukla