Reputation: 18704
When I navigate from my dashboard, to an account with an id of 1234 (For example), my URL goes from:
example.com/
to
example.com/account/1234
This works.
But then I want to go to account 5678. So while on my account screen, I try to navigate to:
example.com/5678
The URL changes in the browser - but the page doesn't load. I think, because the path, excluding the ID, hasn't changed.
So it went from example.com/1234
to example.com/5678
I'm using BrowserRouter
My Route is setup:
<Route exact path="/account/:id" component={AccountEditor} />
And my link is this:
<Link to={{ pathname: `/account/${this.props.accountId}`, state: params}}>{this.props.name}</Link>
How can I make it allow a change, when the component remains the same, but the ID changes?
How I use Routes, and this is possibly wrong, because I'm new to this, but it's woriing so far, except for this issue is - I have a mainLayout component. It's devided into two columns. A fixed column on the left which shows info on all pages, and then the main section, which changes based on the selected URL.
<Row>
<Col md="2">
<LeftInfoBar />
</Col>
<Col md="10">
<RouteManager />
</Col>
</Row>
The component, RouteManager, has all the components in it like this:
class RouteManager extends React.Component {
render() {
return (
<Switch>
<Route exact path="/" component={Dashboard} />
<Route exact path="/accounts" component={Accounts} />
<Route exact path="/accounts/:id" component={Accounts} />
... lots of other components...
</Switch>
)
}
}
export default RouteManager
Upvotes: 0
Views: 122
Reputation: 272
The page component will not unmount and then mount because only the URL params are changing and not the route of "/account". What I use in this case is a check if componentDidUpdate that uses the id from props.
This goes inside of your Account page component. You don't have to change any of the routes for this.
componentDidUpdate(prevProps) {
if (this.props.match.params.id !== prevProps.match.params.id) {
this.setState({ ['someStateProperty']: newValue })
}
}
You'll have to edit the setState to whatever you use, but this will trigger a rerender. If you need to use an api call, you can also use a fetch to get new data inside of that if
conditional and save the resulting value to state.
Upvotes: 2