第一步写一个404页面
class NotFoundPage extends PureComponent{
render() {
return <div className="notFundPageBox">
<div className="box_404">
<a href="#/index" className="btnBackH">没有找到相应页面</a>
</div>
</div>
}
}
定义404页面路由
import Imported from 'react-imported-component';
import {Route} from 'react-router-dom';
const notFoundPage = Imported(() => {
return import(/* webpackChunkName: "notFoundPage" */ 'containers/notFundPage')
});
const NotFundPageRoutes = () => (
<Route component={notFoundPage}/>
);
export default NotFundPageRoutes;
第二步找到跟路由
import { Route, Switch } from 'react-router-dom';
import HomeRoutes from '../containers/home/router';
import Test1Routes from '../containers/test1/router';
import Test2Routes from '../containers/test2/router';
import NotFundPageRoutes from '../containers/notfundpage/router';
const AllRoutes = () => (
<div>
<Switch>
<Route exact path='/index' component={HomeRoutes}/>
<Route path='/test1' component={Test1Routes}/>
<Route path='/test2' component={Test2Routes}/>
<Route path='*' component={NotFundPageRoutes}/>
</Switch>
</div>
);
export default AllRoutes;
exact 指严格匹配路径,如果homepage路由只有一个/index ,可以设置严格匹配
找到子路由
import {Route} from 'react-router-dom'
import Imported from 'react-imported-component';
import {homeReducer} from './reducers'
import CommonUtil from '../../util/CommonUtil';
const IndexPage = Imported(() => {
CommonUtil.injectReducer({home: homeReducer}); //注册reduce
return import(/* webpackChunkName: "IndexPage" */ 'containers/home/IndexPage')
});
const HomePage = () => (
<Route exact path='/index' component={IndexPage}/>
);
export default HomePage;
后面匹配子路由均和上方一致即可
import Imported from 'react-imported-component';
import {Route,Switch} from 'react-router-dom';
import {homeReducer} from "../home/reducers";
import NotFundPageRoutes from '../containers/notfundpage/router';
const TestComponent = Imported(() => {
CommonUtil.injectReducer({home: homeReducer}); //注册reduce
return import(/* webpackChunkName: "TestComponent" */ 'containers/TestComponent')
});
const Test1Routes = () => (
<div>
<Switch>
<Route exact path='/test/list/:type' component={TestComponent}/> //exact严格模式
<Route path='*' component={NotFundPageRoutes}/>
</Switch>
</div>
);
export default Test1Routes;
子项路由进行严格匹配
弱匹配404不能出现
打开网址,随便输入路径,未能在Router中匹配到的路由,均显示404 未找到页面