在react-router4中,除了在路由文件中还可以在页面中写路由组件
dva初始化项目中router.js文件的内容如下
import React from 'react';
import { Router, Route, Switch } from 'dva/router';
import IndexPage from './routes/IndexPage';
function RouterConfig({ history }) {
return (
);
}
export default RouterConfig;
页面中的路由:
import React from 'react';
import { Router, Route, Switch } from 'dva/router';
import IndexPage from './routes/IndexPage';
class Products extends React.Component {
render() {
return (
)
}
}
一、引用react-router-dom
react-router-dom是用于DOM绑定的 React Router, 比react-router多出了这样的DOM类组件
import { Router, Route, Switch, Redirect } from 'react-router-dom';
二、组件-
// 用于导航的历史对象
// 一个使用了 HTML5 history API 的高阶路由组件,保证你的 UI 界面和 URL 保持同步
// Hash history 不支持 location.key 和 location.state。
// 另外由于该技术只是用来支持旧版浏览器,因此更推荐大家使用 BrowserRouter
三、组件-
如果你访问 /about,那么组件 About User Nomatch 都将被渲染出来,因为他们对应的路由与访问的地址 /about 匹配
四、组件-
Home} // 内联渲染
/>
五、组件-
// 通过from匹配路由重定向
// 通过render重定向
(
loggedIn ? (
) : (
)
)}/>
六、组件-
// to为string
// to为obj
// replace
// replace(bool):为 true 时,点击链接后将使用新地址替换掉访问历史记录里面的原地址;
// 为 false 时,点击链接后将在原有访问历史记录的基础上添加一个新的纪录。默认为 false;
七、组件-
About
FAQs
FAQs
Event 123
八、对象-history
history 对象通常具有以下属性和方法:
- length: number 浏览历史堆栈中的条目数
- action: string 路由跳转到当前页面执行的动作,分为 PUSH, REPLACE, POP
-
location: object 当前访问地址信息组成的对象,具有如下属性:
pathname: string URL路径 search: string URL中的查询字符串 hash: string URL的 hash 片段 state: string 例如执行 push(path, state) 操作时,location 的 state 将被提供到堆栈信息里,state 只有在 browser 和 memory history 有效。
- push(path, [state]) 在历史堆栈信息里加入一个新条目。
- replace(path, [state]) 在历史堆栈信息里替换掉当前的条目
- go(n) 将 history 堆栈中的指针向前移动 n。
- goBack() 等同于 go(-1)
- goForward 等同于 go(1)
- block(prompt) 阻止跳转
九、对象-location
location 是指你当前的位置,将要去的位置,或是之前所在的位置
{
key: 'ac3df4', // not with HashHistory!
pathname: '/somewhere'
search: '?some=search-string',
hash: '#howdy',
state: {
[userDefined]: true
}
}
在以下情境中可以获取 location 对象
- 在 Route component 中,以 this.props.location 获取
- 在 Route render 中,以 ({location}) => () 方式获取
- 在 Route children 中,以 ({location}) => () 方式获取
- 在 withRouter 中,以 this.props.location 的方式获取
可以在不同情境中使用 location:
history.push(location)
history.replace(location)
十、对象-match
const Topics = ({ match }) => (
Rendering with React
);
match 对象包含了
- params: object 路径参数,通过解析 URL 中的动态部分获得键值对
- isExact: bool 为 true 时,整个 URL 都需要匹配
- path: string 用来匹配的路径模式,用于创建嵌套的
- url: string URL 匹配的部分,用于嵌套的
在以下情境中可以获取 match 对象
- 在 Route component 中,以 this.props.match获取
- 在 Route render 中,以 ({match}) => () 方式获取
- 在 Route children 中,以 ({match}) => () 方式获取uter 中,以 this.props.match的方式获取matchPath 的返回值
当一个 Route 没有 path 时,它会匹配一切路径。
具体实例可参考 https://reacttraining.com/rea...