I am using react-router v4 and am having a little trouble with nested routes. My parent route is a product detail page that uses an AJAX request within componentDidMount() to set the product data.
But when I click a link to render a route nested in the detail page the parent route re-renders and does the AJAX request a second time?
Here is some quick example code:
const App = () => (
<Router>
<Switch>
<Route path="/login" component={LoginPage} />
<Route path="/admin" component={AdminPage} />
</Switch>
</Router>
)
const AdminPage = ({match}) => (
<Switch>
<Route exact path={match.path} component={Home} />
<Route path={`${match.path}/products/:id`} component={ProductDetails} />
<Route path={`${match.path}/products`} component={ProductList} />
</Switch>
)
class ProductDetails extends React.Component {
constructor(){
super();
this.state = {
name: '',
price: ''
};
}
componentDidMount(){
API.getProductDetails((response) => {
this.setState({
name: response.name,
price: response.price
});
})
}
render(){
return(
<div>
<h1>{this.state.name}</h1>
<p>{this.state.price}</p>
<ul>
<li><Link to={`${this.props.match.url}/stats}>Stats</Link></li>
<li><Link to={`${this.props.match.url}/bids}>Bids</Link></li>
<li><Link to={`${this.props.match.url}/third}>Third</Link></li>
</ul>
<Switch>
<Route path={`${this.props.match.path}/stats} component={Stats} />
<Route path={`${this.props.match.path}/bids} component={Bids} />
<Route path={`${this.props.match.path}/third} component={Third} />
</Switch>
</div>
);
}
}
So how would I prevent the parent component (ProductDetails) from re-rendering when I open one of the routes nested in it? Thank you for any help!
<Route path="/products/:id/:type" component={FooContainer} />
and handle your request in this one depending on the type. The nested is unnecessary. – soupette