【发布时间】:2018-08-17 07:29:26
【问题描述】:
我创建了组件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 页面,但该组件也出现在每个现有页面中。我该如何解决这个问题?
【问题讨论】:
-
使用 Switch 标签来包装你的路由。这样只有一条路线被渲染。另外,将您未找到的路线放在路线的最底部并删除路径属性。
标签: javascript reactjs http-status-code-404