Constellates Constellates -4 years ago 304
React JSX Question

Component does not remount when route parameters change

I working on a react application using react-router. I have a project page that has a url as follows.

When the project component loads, I trigger a data request for that project from the componentDidMount event. I'm now running into an issue where if I switch directly between two projects so only the id changes like this...

componentDidMount is not triggered again so the data is not refreshed. Is there another lifecycle event I should be using to trigger my data request or a different strategy to tackle this issue?

Answer Source

If the link is directing to the same route with just a different param, it's not remounting, but instead receiving new props. So, you could use the componentWillReceiveProps(newProps) function and look for newProps.params.projectId.

If you're trying to load data, I would reccomend fetching the data on before the router handles the match using static methods on the componet. Check out this example. React Router Mega Demo. That way, the component would load with the data and automatically update when the route params change without needing to rely on componentWillReceiveProps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download