coexsystem coexsystem - 3 months ago 30
React JSX Question

React-router: Refreshing the child page contents with hashHistory.push

I'm working on an SPA that uses the react router like so:

<Router>
<Route path="/" component={Base}>
<IndexRoute component={Home}/>
<Route path="features/:id" component={Single} />
</Route>
</Router>


I have a component attached to the Base that is supposed to update the contents of Single via:

hashHistory.push(`features/${val.value}`);


The page url updates successfully but once I am in the child Route, the change to hashHistory doesn't cause the child state to update. Any ideas how I can reload the content here?

Answer

You need to add the componentWillReceiveProps lifecycle method. This will respond to prop changes for all renders except the initial one. Recall that everything coming from the router is really just a prop.

// Example: the feature id changed in the url
componentWillReceiveProps(nextProps) {
  if (this.props.params.id !== nextProps.params.id) {
    this.setState(...);
  }
}