我创建了组件NotFound
,当我转到一个不存在的页面时它可以正常工作。但是它出现在我所有页面中的同一页面,不仅仅是那个不存在的页面。这是组件:
import React from 'react'
const NotFound = () =>
<div>
<h3>404 page not found</h3>
<p>We are sorry but the page you are looking for does not exist.</p>
</div>
export default NotFound
这就是我在主页面中使用它的方式:
class MainSite extends Component {
render () {
return (
<div>
{/* Render nav */}
<Route path='/dashboard' component={Nav} />
<Route path='/retrospectives' component={Nav} />
<Route path='/users' component={Nav} />
<Route path='/projects' component={Nav} />
{/* Dashboard page */}
<ProtectedRoute exact path='/dashboard' component={DashboardPage} />
{/* Retrospectives page */}
<ProtectedRoute exact path='/retrospectives' component={RetrospectivesPage} />
{/* Users page */}
<ProtectedRoute exact path='/users' component={UsersPage} />
{/* Projects page */}
<ProtectedRoute exact path='/projects' component={ProjectsPage} />
{/* Retrospective related pages */}
<Route exact path='/retrospectives/:retrospectiveId' component={Retrospective} />
<Route exact path='/join-retrospective' component={JoinRetrospective} />
<ProtectedRoute exact path='/create-retrospective/:retrospectiveId' component={Retrospective} />
{/* OnBoarding pages */}
<ProtectedRoute exact path='/beta-code' component={BetaCodeAccess} />
<Route exact path='/auth-handler' component={AuthHandler} />
<Route exact path='/join-organization' component={JoinOrganization} />
</div>
)
}
}
export default MainSite
正如您所看到的,我使用<Route path="*" component={NotFound} />
创建了404页面,但该组件也出现在每个现有页面中。我该如何解决这个问题?
答案 0 :(得分:6)
下面的所有示例都可以正常工作:
<Route path="" component={NotFound} /> // empty ""
<Route path="*" component={NotFound} /> // star *
<Route component={NotFound} /> // without path
或者如果您想返回不带任何组件的简单404消息:
<Route component={() => (<div>404 Not found </div>)} />
答案 1 :(得分:5)
试试这个:
flat_map
答案 2 :(得分:2)
尝试一下:
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>
答案 3 :(得分:1)
只需从Switch
导入react-router-dom
,然后将所有路由包装在交换组件中。同样重要的是要注意将404Page组件保持在最底部(恰好在您的switch结束标记之前),这样,它将首先将每个组件与其路由进行匹配。如果匹配,它将渲染该组件,否则检查下一个组件。最终,如果将找不到匹配的路由,它将呈现404Page