React Router的history探究

目录

前言

  路由是单页应用中十分重要的概念。具体在react中,react-router为我们提供了一套完整的路由机制。

概述

  项目history相关文档主页:Histories。文档的讲解十分详细。本文只是通过在实际项目中history的状态变化进行简单小结。以dva应用为例,

经过这样的配置后,容器组件可以在props中拿到history对象和相关参数。


表现


如上所示,history中包含了一系列方法,这里主要选择两个进行说明:

  1. history.listen()
      利用这个函数可以对路由变化进行监听,从而触发其他事件:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    subscriptions: {
    setup({ dispatch, history }) {
    history.listen(location => {
    if(location.pathname === '/home'){
    dispatch({type: 'query'});
    }
    })
    }
    },

2.history.goBack()
  利用此函数可以实现回退,回到上一个路由所匹配的组件,但是无法记录上一个页面的状态:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class LiveDetail extends Component {
constructor(props, context) {
super(props, context);

this.goBack = this.goBack.bind(this);
}

static contextTypes = {
router: React.PropTypes.object.isRequired
};

goBack(){
this.context.router.goBack();
}

componentWillReceiveProps(nextProps) {
...
}

render() {
....
}
}