简体   繁体   中英

How do i add an error page to my react router code?

so this is my code

              <Router>
                <Route path="/" component={Nav}/>
                <Route path="/" exact component={Home}/>
                <Route path="/updates" exact component={Updates} />
                <Route path="/author" exact component={Author} />
                <Route path="/" component={Footer}/>
              </Router>

It works completely fine i just have a slight problem with it. If i were to go to lets say Author page i can just type /author and it will show not only the author but the navbar and footer because i didn't make them exact on purpose but the problem is if i were to make a random link such as ./ejfjife it will still show the navbar and footer i want to make it so if the user made up a link that doesn't exist it'll redirect them to some kind of 'this page doesn't exist' error

thank you

If you always want your Nav and Footer to be present, they shouldn't even be listed under a Route . They can exist outside your Router . Then your Home component can take a path="/" exact and any other route can take the path="/" Component={Error404} . Like this:

<App>

  <Nav />

  <Router>
    <Route path="/" exact component={Home}/>
    <Route path="/updates" exact component={Updates} />
    <Route path="/author" exact component={Author} />
    <Route path="/" component={Error404}/>
  </Router>

  <Footer />

</App>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM