本篇内容:

  • 单一的路由无嵌套
  • 多层嵌套路由
  • 获取路径中的参数
  • 按需加载

单一的路由无嵌套

routers.js

import Home from 'components/Home';
import News from 'components/News';
import User from 'components/User';
import My from 'components/My'; let routes=[
{
path:'/',
component:Home ,
exact:true
},
{
path:'/news',
component:News ,
},
{
path:'/user',
component:User
},
{
path:'/my',
component:My
},
]
export default routes;

App.jsx

import React, { Component } from 'react';
import { HashRouter as Router, Switch, Route } from "react-router-dom";
import routes from '../routers/index';
class App extends Component {
render() {
return (
<Router>
<div>
<Switch>
//主要逻辑在这里
{
routes.map((item, i) => {
if(item.exact){
return <Route exact path={item.path} component={item.component} key={i}/>
}else{
return <Route path={item.path} component={item.component} key={i}/>
}
})
}
</Switch>
</div>
</Router>
);
}
}

多层嵌套路由

let routes=[
{
path:'/hear',
component:Hear,
exact:true,
description:"听",
subs:[
{
path:'/hear/',
component:HearIndex,
description:"听-首页"
},
{
path:'/hear/book',
component:HearBook,
description:"听-课文"
},
]
},
{
path:'/speak',
component:Speak,
exact:true,
description:"说",
subs:[
{
path:'/speak/',
component:CN,
description:"说-汉语"
},
{
path:'/speak/english',
component:English,
description:"说-英语"
},
]
},
{
path:'/read',
component:Read,
exact:true,
description:"读",
subs:[
{
path:'/read/',
component:ReadBook,
description:"读-课文"
},
{
path:'/read/newspaper',
component:ReadNews,
description:"读-报纸"
},
]
},
{
path:'/writ',
component:Writ,
exact:true,
description:"写"
}
]
export default routes;

App.jsx

{
routes.map((item, i) => {
if (item.exact) {
//官方固定格式
return <Route exact path={item.path} key={i} render={ props => (<item.component {...props} routes={item.subs}/>) />
}
else {
return <Route path={item.path} key={i} render={ props => (<item.component {...props} routes={item.subs}/>)} />
}
})
}

//step 2,在对应的组件中再次遍历

{
this.props.routes.map((item, i) => {
return <Route exact path={item.path}
component= {item.component}
key={i}/>
})
}

跳转

this.props.history.push(`/about/type/${id}`)
this.props.history.replace(...)

注意:

不能在子组件中直接获取,需要从父级传入之后用props获取;

跳转时,如果还有事件未结束,则容易报错!

如:

<LoginCom TIMEID={TIMEID} {...this.props}/>

获取路径参数

获取对应的params

this.props.match.params.id

获取?后面对应的值

const getQueryString = (str,name) => {
let result = str.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
if (result == null || result.length < 1) {
return "";
}
return decodeURI(result[1], "utf-8");
}

如:http://localhost:3000/#/textbook/bishun?val=看

console.log(getQueryString(this.props.location.search,'val'));

按需加载

感觉这种方式最简单:

基于 webpack, babel-plugin-syntax-dynamic-import, 和 react-loadable;

主要是利用了react-loadable这个高级组件,他是专门用来异步加载(也可以预加载)组件的。

cnpm i -S react-loadable @babel/plugin-syntax-dynamic-import

.babelrc

{
“ presets ”:[ “ @ babel / react ” ],
“ plugins ”:[ “ @ babel / plugin-syntax-dynamic-import ” ]
}

routers.js变化

import Loadable from 'react-loadable';
import DelayLoading from './DelayLoading'; const Home= Loadable({loader: () => import('../components/Home'), loading : DelayLoading,delay:3000})
const Login= Loadable({loader: () => import('../components/Login'), loading : DelayLoading,delay:3000})

打包文件情况对比:

首屏加载情况对比:

参考文档:

https://reacttraining.com/react-router/web/example/route-config

https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/guides/code-splitting.md

https://github.com/jamiebuilds/react-loadable

可参考其他文章:https://www.cnblogs.com/alan2kat/p/7754846.html

React进阶篇(1) -- react-router4模块化的更多相关文章

  1. React进阶篇学习

    继续上一次基础篇, 分享一些关于React的进阶技术 React 进阶部分 ** context ** ** setState vs forceUpdate ** ** Mixins ** ** HO ...

  2. React进阶篇(2) -- Redux

    前言 如果还不知道为什么要使用Redux,说明你暂时还不需要它. 三大原则 单一数据源 整个应用的 state 被储存在一棵 object tree 中,并且这个 object tree 只存在于唯一 ...

  3. 当初要是看了这篇,React高阶组件早会了

    当初要是看了这篇,React高阶组件早会了. 概况: 什么是高阶组件? 高阶部件是一种用于复用组件逻辑的高级技术,它并不是 React API的一部分,而是从React 演化而来的一种模式. 具体地说 ...

  4. React进阶之高阶组件

    前言 本文代码浅显易懂,思想深入实用.此属于react进阶用法,如果你还不了解react,建议从文档开始看起. 我们都知道高阶函数是什么, 高阶组件其实是差不多的用法,只不过传入的参数变成了react ...

  5. React进阶之路书籍笔记

    React进阶之路: "于复合类型的变量,变量名不指向数据,而是指向数据所在的地址.const命令只是保证变量名指向的地址不变,并不保证该地址的数据不变,所以将一个对象声明为常量必须非常小心 ...

  6. React基础篇学习

    到今天为止, 使用react已经一年了, 现在整理一下入门时的一些重要知识, 帮助想要学习react的同学们理解某些内容. React 元素 React 元素,它是 React 中最小基本单位,我们可 ...

  7. react基础篇入门组件

    讲述一下React: 1.声明式设计-React采用声明范式,可以轻松描述应用 2.高效-React通过DOM模型,最大限度的减少dom的交互 3.灵活-React可以与已知的库或框架很好的配合 4. ...

  8. react基础篇六

    创建 Refs 使用 React.createRef() 创建 refs,通过 ref 属性来获得 React 元素.当构造组件时,refs 通常被赋值给实例的一个属性,这样你可以在组件中任意一处使用 ...

  9. [转] React 最佳实践——那些 React 没告诉你但很重要的事

    前言:对很多 react 新手来说,网上能找到的资源大都是些简单的 tutorial ,它们能教会你如何使用 react ,但并不会告诉你怎么在实际项目中优雅的组织和编写 react 代码.用谷歌搜中 ...

随机推荐

  1. phpStudy启动失败时的解决方法 提示缺vc9运行库

    问题描述: 问题产生原因分析: php5.3.5.4和apache都是用vc9编译,电脑必须安装vc9运行库才能运行. php5.5.5.6是vc11编译,如用php5.5.5.6必须安装vc11运行 ...

  2. Redhat 无线(Wifi)上网命令行配置

    小结两种命令行模式下配置无线wife的方法,实践测试通过(Red Hat Enterprise Linux release 6.0 Beta(Santiago)) 一.使用wpa_supplicant ...

  3. Spring AOP 中pointcut expression表达式解析及配置

    Pointcut是指那些方法需要被执行”AOP”,是由”Pointcut Expression”来描述的. Pointcut可以有下列方式来定义或者通过&& || 和!的方式进行组合. ...

  4. json转字符串 —— jsonObj.toJSONString()与JSON.stringify(jsonObj)

    ar people = { "programmers": [{ "firstName": "Brett", "lastName&q ...

  5. dyld_decache&MesaSQLite

    [dyld_decache] Starting from iPhone OS 3.1, the individual libraries files supplied by the system ar ...

  6. Professional C# 6 and .NET Core 1.0 - Chapter 38 Entity Framework Core

    本文内容为转载,重新排版以供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处:Professional C# 6 and .NET Core 1.0 - Chapter 38 Entity F ...

  7. SpringBoot20 集成SpringSecurity02 -> 利用SpringSecurity进行前后端分离的登录验证

    1 SpirngBoot环境搭建 创建一个SpringBoot项目即可,详情参见三少的相关博文 参考博文 -> 点击前往 SpirngBoot项目脚手架 -> 点击前往 2 引入Spirn ...

  8. Nginx+Tomcat集群+session共享

    Nginx+Tomcat集群+session共享 1)安装Nginx 2)配置多个Tomcat,在server.xml中修改端口(端口不出现冲突即可) 3)在nginx.conf文件中配置负载均衡池, ...

  9. Net-tools

    一.简介 Net-tools 包含如下程序,构成了 Linux 网络的基础. arp用来操作核心的ARP(地址解析协议)的高速缓存,通常用来增加.删除一个条目以及转储ARP高速缓存. dnsdomai ...

  10. BOOL运算符号(从C#入门经典第五版中摘录)

    只总结自己觉得难的哈: (1) var1=!var2;    //(非) (2) var1=var2&var3;    //(与) (3)var1=var2|var3;    //(或) (4 ...