我是React的新手,我只想知道如何将用户从404错误页面重定向到主页,这是我在GitHub The project Github repository 上的项目仓库
这是我的路线代码
import React, {Component} from 'react';
import { BrowserRouter, Route, Switch, Link, Redirect } from 'react-router-dom';
import Home from './components/home';
import About from './components/about';
import Contact from './components/contact';
import Navbar from './components/navbar';
import NotFound from './components/404';
class Routes extends Component {
render(){
return(
<BrowserRouter>
<div>
<Navbar />
<Switch>
<Route path='/' component={Home} exact />
<Route path='/home' component={Home} />
<Route path='/about' component={About} />
<Route path='/contact' component={Contact} />
<Route component = {NotFound}/>
</Switch>
</div>
</BrowserRouter>
);
}
}
export default Routes;
答案 0 :(得分:0)
如果您想立即从404重定向到主页(没有看到NotFound
组件),则可以使用以下代码替换最后一个Route(<Route component = {NotFound}/>
):
<Redirect to="/" />
这应该捕获所有与其他路由都不匹配的路径,就像NotFound路由之前一样,但是它不会呈现组件,而是会将用户转到首页。