Freddie Freeston
Freddie Freeston

Reputation: 1

React - Component Will Mount not getting called when changing routes?

When changing from indexRoute to the Route with path ':topic', the page just stays the same.

My routes look like this:

ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory}>
  <Route path='/' addHandlerKey={true} component={App}>
    <IndexRoute component={ArticleList} />
    <Route path='/:topic'  component={ArticleList} />
    <Route path='/:id' component={Article} />
  </Route>
</Router>
</Provider>, document.getElementById('app'));

ArticleList looks like this:

const _ArticleList = React.createClass({

componentWillMount () {
  this.props.fetchArticles();
},

render () {
  return (
  <div id='ArticleList' className='box'>
     {this.props.articles.map(function (article, i) {
      return <ArticleCard id={article._id} key={i} title={article.title} votes={article.votes} />;
     })}
  </div>
 );
}

When I navigate to the route then refresh the page, it changes to what I want, just not when navigating to it directly.

To be clear, the url is changing (thanks to App component) so params.topic is changing but the component is not re-rendering so componentWillMount is not getting triggered. (Have tried componentWillReceiveProps but this didnt work)

Upvotes: 0

Views: 6000

Answers (2)

duhaime
duhaime

Reputation: 27574

I noticed the same behavior when I had attempted to use conponentWillMount() -- which is a misspelling of componentWillMount().

The misspelling didn't trigger any warnings or errors, and of course didn't trigger the events I intended to call.

Upvotes: -1

finalfreq
finalfreq

Reputation: 6980

The problem you are running into is that once the index page has loaded the component will have mounted and wont unmount unless you change to a completely different route all together. You are just updating a child route which doesn't retrigger the componentWillMount to fire off again.

You need to revisit componentWillReceiveProps because that would be the right way to do this.

something like:

componentWillReceiveProps(nextProps) {
 // in our own app we have acces to routeParams as the :id portion not sure if that works on your app
 // but idea should be if the topic has changed then refetch the articles 


  if (this.props.routeParams !== nextProps.routeParams) {
    this.props.fetchArticles();
  }
}

Upvotes: 3

Related Questions