13:编程路由之高阶组件(间接跳转)

一个组件内没有直接被路由接管(比如下载component没有直接注册在router内)就会访问不到props对象

用到了withRouter

比如在mine.jsx(router配置过)内

引入自定义的 <Minedemo/>

此时Minedemo内直接打props是没有路由信息的

使用例子:

import {withRouter} from 'react-router-dom'

class MineDemo extends React.Component{
click(){
console.log(this.props)//当前组件没有被路由直接管理 -需要用到高阶组件 widthRouter
// 接管后的props就不再是空对象 可以正常使用了
this.props.history.replace('/home')

}
render(){
return (
<div>
<button onClick={this.click.bind(this)}>回到home</button>
</div>
)
}
}

//高阶组件
export default withRouter(MineDemo)

例2:

import React, {Component} from 'react'
import {NavLink, Route, Switch, withRouter} from 'react-router-dom';
import { Layout, Menu, Breadcrumb,Collapse,Button } from 'antd';
const { Header, Content, Footer } = Layout;
// import './index.css'
class Nav extends Component {
    constructor(props){
        super(props)
        this.state = {
        }
    }
    componentWillMount(){
    }
    componentDidMount(){
        //dom操作放在这里面  请求数据也建议放在这里
        console.log(this.props.history.location.pathname)
    }
    render(){
        // console.log(this.state.defaulS)//放在componentDidMount 会一直是初始值null
        const pathname = this.props.history.location.pathname
        let defaulS = []
        defaulS.push(pathname)
        console.log(defaulS)//实时根据当前路径更新
        return (
            // <ul>
            //   <li><Link to='/home'>首页</Link></li>
            //   <li><Link to='/about'>关于</Link></li>
            //   <li><Link to='/topics'>主题列表</Link></li>
            //   <li><Link to='/mine'>我的</Link></li>
            //   <li><Link to='/mine/Ucenter'>用户详情</Link></li>
            // </ul>
                // <ul>
                // <li><NavLink activeStyle={{color:'green',background:'yellow'}} to='/home'>首页</NavLink></li>
                // <li><NavLink activeClassName='select' to='/about'>关于</NavLink></li>
                // </ul>
                <Header>
                    <div className="logo" />
                    {/* 原defaultSelectedKeys不能用只能初始化加载 二次导航进入会失效 */}
                    <Menu theme="dark" mode="horizontal" selectedKeys={defaulS}>
                    <Menu.Item key="/home"><NavLink style={{textDecoration:'none'}} to='/home'>首页</NavLink></Menu.Item>
                    <Menu.Item key="/debug"><NavLink style={{textDecoration:'none'}} to='/debug'>调试</NavLink></Menu.Item>
                    <Menu.Item key="/creat"><NavLink style={{textDecoration:'none'}} to='/creat'>创建节目</NavLink></Menu.Item>
                    <Menu.Item key="/login"><NavLink style={{textDecoration:'none'}} to='/login'>退出</NavLink></Menu.Item>
                    <Menu.Item key="/other" onClick={this.fnTurn}>其它</Menu.Item>
                    </Menu>
                </Header>
        )
    }
}
export default withRouter(Nav);

 

posted @ 2020-08-27 15:13  少哨兵  阅读(210)  评论(0编辑  收藏  举报