我创建了组件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页,但该组件也出现在现有的每个页面中。我怎么才能解决这个问题?
发布于 2018-03-08 20:17:18
试试这个:
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>发布于 2020-02-18 12:15:39
下面的示例都很好:
<Route path="" component={NotFound} /> // empty ""
<Route path="*" component={NotFound} /> // star *
<Route component={NotFound} /> // without path或者,如果您想返回一个没有任何组件的简单404消息:
<Route component={() => (<div>404 Not found </div>)} />发布于 2021-11-08 05:20:58
对于那些使用react-router-dom v6寻找答案的人来说,许多事情都发生了变化。例如,Switch不再存在,您必须使用element而不是component,.看看这个小例子,给你一个想法:
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import './index.css'
import App from './App'
const Test = () => (
<h1>404</h1>
)
ReactDOM.render(
<React.StrictMode>
<Router>
<Routes>
<Route path='/' element={<App />} />
<Route path='*' element={<Test />}/>
</Routes>
</Router>
</React.StrictMode>,
document.getElementById('root')
)这样,您将定义您的home路由,所有其他路由都将显示404。有关更多信息,请查看官方指南。
https://stackoverflow.com/questions/49181678
复制相似问题