问题
Have a question regarding react router.
I have a header item that I would like to display for all routes. And of course, I want this to be part of the so that the user can click items from a nav.
Currently I have my <Header />
outside of my <Router>
and I guess this isn´t working since my router then don't know to re-render?
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
<div>
<Header />
<Router>
<Switch>
<Route exact path="/" component={Posts} />
<Route exact path="/:category/:postId" component={PostDetails} />
<Route path="/:category" component={CategoryView} />
</Switch>
</Router>
</div>
And my header has for example a <Link to="/">LOGO</Link>
回答1:
My comment in answer:
class App extends Component {
render() {
return (
<BrowserRouter>
<div>
<Header />
<Switch>
<Route exact path="/" component={Posts} />
<Route exact path="/:category/:postId" component={PostDetails} />
<Route path="/:category" component={CategoryView} /
</Switch>
<Footer />
</div>
</BrowserRouter>
);
}
}
回答2:
When you change location but the same route is matching, your component is not remounting, just receiving new props.
Therefore, you can use the componentWillReceiveProps hook to update your component using the new route params (e.g. nextProps.match.params.category):
...
componentWillReceiveProps(nextProps) {
// Update component using nextProps
}
...
来源:https://stackoverflow.com/questions/46807549/react-router-display-one-component-for-all-routes-a-header