404 page in REACT

前端 未结 4 1595
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-01 23:48

I created the component NotFound and it works fine when I go to a page that doesn\'t exist. But the same page it\'s appearing in all my pages, not only the one

相关标签:
4条回答
  • 2021-01-01 23:59

    All below example works fine:

    <Route path="" component={NotFound} /> // empty ""
    <Route path="*" component={NotFound} /> // star *
    <Route component={NotFound} /> // without path
    

    Or if you want to return a simple 404 message without any component:

    <Route component={() => (<div>404 Not found </div>)} />
    
    0 讨论(0)
  • 2021-01-01 23:59

    Try This:

    import React from "react";
    import { Redirect, Route, Switch, BrowserRouter } from 'react-router-dom';
    import HomePage from './pages/HomePage.jsx';
    import NotFoundPage from './NotFoundPage.jsx';
    class App extends React.Component {
        render(){
            return(
                <BrowserRouter>
                    <Switch>
                        <Route exact path='/' component={HomePage} />
                        <Route path="*" component={NotFoundPage} />
                    </Switch>
                </BrowserRouter>
            )
        }
    }
       
    export default App;
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

    0 讨论(0)
  • 2021-01-02 00:01

    Try this one:

      import { Switch, Route } from 'react-router-dom';
    
      <Switch>
        <Route path='/dashboard' component={Nav} />
        <Route path='/retrospectives' component={Nav} />
        <Route path='/users' component={Nav} />
        <Route path='/projects' component={Nav} />
    
        <Route path="" component={NotFound} />
      </Switch>
    
    0 讨论(0)
  • 2021-01-02 00:02

    Simply import Switch from react-router-dom and wrap all your Routes in the Switch Component. Also Important here is to note to keep your 404Page component at the very bottom(just before your switch ending tag) This way it will match each component with its route first. If it matches, it will render the component or else check the next one. Ultimately if none matching routes will be founded, it will render 404Page

    0 讨论(0)
提交回复
热议问题