首页 前端知识 React-Router-Dom 配置404页面

React-Router-Dom 配置404页面

2024-06-07 00:06:12 前端知识 前端哥 416 639 我要收藏
  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 未找到页面

转载请注明出处或者链接地址:https://www.qianduange.cn//article/11152.html
标签
评论
发布的文章

1.10 Unity中的数据存储 JSON

2024-06-13 21:06:30

JSON 数据格式化方法

2024-06-13 21:06:26

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!