react-router v4怎样监听路由变化

2018-11-05  本文已影响26人  JaniceD

最近才刚开始学习react,所以直接接触的就是v4版本,一直不知道怎么监听地址栏url的变化,刚才终于在官网找到了一个解决方案,记录一下

实现目标:直接改变地址栏的值,页面中header组件对应的内容也改变


后台管理系统界面

history

官方文档说使用history
链接:https://github.com/ReactTraining/history

具体步骤

1.新建一个全局变量文件constants.js

import { createBrowserHistory } from 'history'

let history = new createBrowserHistory();
global.constants = {
    history:history
}

2.在router.js路由组件中监听路由变化

componentDidUpdate(){
        //test方法是父组件方法
        //global.constants.history是上一步定义的全局变量
        this.props.test(global.constants.history.location.pathname);
    }

3.父组件admin.js中根据路由传过来的参数pathname得到对应的title(中文)

test =(pathname) =>{
        let _this = this;
        //menuConfig是菜单的配置文件
        for(let i=0;i<menuConfig.length;i++){
            if(menuConfig[i].children){
                let child = menuConfig[i].children;
                for(let j=0;j<child.length;j++){
                    if(child[j].key===pathname){
                        //调用header子组件方法,改变title
                        _this.refs.header.updateCurrentTitle(child[j].title);
                        return;
                    }
                }
            }else{
                let item = menuConfig[i];
                if(item.key===pathname){
                    //调用header子组件方法,改变title
                    _this.refs.header.updateCurrentTitle(item.title);
                    return;
                }
            }
        }
    };

4.menuConfig.js配置文件大致结构

const menuList = [
    {
        title: '首页',
        key: '/home',
        icon:"home"
    },
    {
        title: 'UI',
        key: '/ui',
        icon:"scan",
        children: [
            {
                title: '按钮',
                key: '/ui/buttons'
            },
            {
                title: '通知提醒',
                key: '/ui/notification'
            },
            {
                title: '全局Message',
                key: '/ui/messages'
            }
        ]
    },
    {
        title:'表单',
        key:'/form',
        icon:'file-text',
        children:[
            {
                title:'登录',
                key:'/form/login'
            },
            {
                title:'注册',
                key:'/form/reg'
            }
        ]
    },
    ......
]
export default menuList;

5.(important!)点击菜单项,调用history.push方法

   //菜单组件menuLeft.js
    testSelect =(path)=>{
        global.constants.history.push(path.key);
    }

Menu加上onSelect属性,触发setCurrentTitle方法

<Menu
      mode="inline"
      className="menuList"
      defaultOpenKeys={this.state.openKeys}
      theme="dark"
      onOpenChange = {this.onOpenChange}
      defaultSelectedKeys={this.state.current}
      onSelect={this.testSelect}
>
上一篇 下一篇

猜你喜欢

热点阅读