1. 程式人生 > 實用技巧 >13:程式設計路由之高階元件(間接跳轉)

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);