React Router display one component for all routes ( a header)

浪尽此生 提交于 2021-02-19 05:43:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!