Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Router - componentDidMount not called when navigating to URL

Tags:

I'm a little stumped on this one. I defined a route called classes/:id. When navigating to that route in the app, the componentDidMount() is called. However, when reloading the page or copying and pasting the URL the page completely loads, but the componentDidMount() method is not called at all.

From what I have read, the reason is because the same component mounted even though the page is being reloaded which is why the lifecycle method does ever get fired off.

What are some ways to handle this? Your help is greatly appreciated. Thanks!

like image 430
wontwon Avatar asked Dec 26 '15 02:12

wontwon


2 Answers

componentDidMount will not be called again if you are already at a classes/:id route. You'll probably want to do something along the lines of:

componentDidUpdate(prevProps) {
  if (this.props.id !== prevProps.id) {
    // fetch or other component tasks necessary for rendering
  }
}
like image 113
DannyRosenblatt Avatar answered Sep 27 '22 19:09

DannyRosenblatt


I try to avoid any mixins (see willTransitionTo), as they are considered harmful.

Although componentDidMount does not fire when changing routes for the same component, componentWillUpdate and componentWillReceiveProps do.

From there, you can detect parameter changes, and can fire your actions accordingly.

like image 34
greygatch Avatar answered Sep 27 '22 18:09

greygatch