React-Router-Dom 配置404页面

  1. 第一步写一个404页面

class NotFoundPage extends PureComponent{
  render() {
    return <div className="notFundPageBox">
    <div className="box_404">
      <a href="#/index" className="btnBackH">没有找到相应页面</a>
    </div>
  </div>
  }
}
  1. 定义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;

  1. 第二步找到跟路由

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;
  1. exact 指严格匹配路径,如果homepage路由只有一个/index ,可以设置严格匹配

  1. 找到子路由

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;
  1. 后面匹配子路由均和上方一致即可

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;
  1. 子项路由进行严格匹配

  1. 弱匹配404不能出现

打开网址,随便输入路径,未能在Router中匹配到的路由,均显示404 未找到页面

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值