问题
My React routes are defined as follows:
...
<Route component={Header} />
<Route exact path="/" component={Landing} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Route component={Footer} />
...
I want to define a catch all route that catches anything that does not match the Landing, About or Contact routes, and instead redirects to a 404 Not found page. How can I do it with React Router 4?
回答1:
Try this implementation
const AppRouter = (props) => {
return (
<BrowserRouter>
<div>
<Header />
<Switch>
<Route component={Header} />
<Route exact path="/" component={Landing} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Route component={Footer} />
<Route component={NotFoundPage} />
</Switch>
</div>
</BrowserRouter>
);
}
回答2:
Not sure if this will work for you as I have some 3rd party babel wrappers in use, but I get away with declaring all my routes then last putting
<Route path="/*" render={() => <SomeComponent /* possible prop injection */ />}/>
I've used this fairly frequently, but you can also use
<Route render={() => <SomeComponent />} />
I don't use this much as I prefer more landmarks in my code, but I got the above from https://tylermcginnis.com/react-router-handling-404-pages/
来源:https://stackoverflow.com/questions/51457480/react-router-4-catch-all-route