React-router: How to reload the component while clicking a link?

Created on 20 Apr 2015  路  3Comments  路  Source: ReactTraining/react-router

I'm using react router to write a forum. The Route of topic page is like <Route name="topicShow" path="topic/:id" handler={TopicShowPage} />.
But if I visit topic/2 from topic/1, the component will not be reload? What's the best way to notify the component when a link is clicked?

// Im my topic component:
 componentWillMount: function () {
        var { id } = this.context.router.getCurrentParams();

        TopicNetworkingActions.getSingle(id, 1);
    },

Most helpful comment

I like to use componentWillReceiveProps:

componentWillReceiveProps: function (nextProps) {
     var id = nextProps.params.id;

     this.setState({
         topic: TopicNetworkingStore.getSingle(id)
    });
}

It prevents a re-render as stated in the docs: ReactJS Component Specs and Lifecycle

All 3 comments

The component doesn't need to be mounted again. Since it is already mounted on the page, it will use the same DOM elements. Try componentWillReceiveProps instead of componentWillMount, although I'm not sure if componentWIllReceiveProps gets called when the component is originally mounted.

I like to use componentWillReceiveProps:

componentWillReceiveProps: function (nextProps) {
     var id = nextProps.params.id;

     this.setState({
         topic: TopicNetworkingStore.getSingle(id)
    });
}

It prevents a re-render as stated in the docs: ReactJS Component Specs and Lifecycle

Thanks a lot, @rgrwkmn , @micahlmartin !

Was this page helpful?
0 / 5 - 0 ratings

Related issues

andrewpillar picture andrewpillar  路  3Comments

winkler1 picture winkler1  路  3Comments

wzup picture wzup  路  3Comments

ackvf picture ackvf  路  3Comments

alexyaseen picture alexyaseen  路  3Comments