package.json 配置修改
1 | -"react-router": "^2.4.0", |
react-router 还是 react-router-dom?
在 React 的使用中,我们一般要引入两个包,react
和 react-dom
,那么 react-router
和react-router-dom
是不是两个都要引用呢?
非也,坑就在这里。它们两个只要引用一个就行了,不同之处就是后者比前者多出了 <Link>
、 <BrowserRouter>
这样的 DOM 类组件。
因此我们只需引用 react-router-dom
这个包就行了。当然,如果搭配 redux
,你还需要使用 react-router-redux
。(what is the diff between react-router-dom & react-router?)
router.js文件修改
- before:
1 |
|
- after:
(ps:官方推荐使用BrowserRouter,但是HashRouter用的人也不少啊!)
1 | import {BrowserRouter as Router,Route,Switch} from 'react-router-dom' |
loctaion对象获取与withRoute
before:
在顶层 Route 的 设置的component 组件往下面传递。
after:
通过withRouter函数包装下,在支持ES7装饰器的环境中,可以直接通过@withRouter获取对象。
1 | import {withRouter} from 'react-router-dom' |
const { match, location, history } = this.props 下图:
(这里要提一下 location.state
,这里 state
的含义与 HTML5 history.pushState
API 中的 state
对象一样。每个 URL 都会对应一个 state
对象,你可以在对象里存储数据,但这个数据却不会出现在 URL 中。实际上,数据被存在了 sessionStorage
中)
发现 location.query
属性没有了,现在通过 query-string
模块进行转换获取。
1 | import queryString from 'query-string' |
页面离开时
before:
路由钩子:
1 | componentDidMount() { |
after:
使用Prompt
组件:
message: string
当用户离开当前页面时,设置的提示信息。
1 | <Prompt message="确定要离开?" /> |
message: func
当用户离开当前页面时,设置的回掉函数
1 | <Prompt message={location => ( |
1 | import createHistory from 'history/createBrowserHistory' (createHashrHistory) |
单独创建history
对象,带来的好处是,在一些store
需要跳转的地方,原来是通过 import { hashHistory } from 'react-router';
获取的,直接 hashHistory.push()
。
4.0以上没有了,需要通过location.history
获取,这样就会要改很多,需要location
传入store
,并且对应的组件大部分需要withRouter
。