路由進階
1.多級路由,和之前的思想一樣,在子路由里面繼續寫Route,繼續掛載組件,就可以實現多級路由
比如這樣:class Food extends Component{
render() {
return (
<Fragment>
<Link to="/food/foodlist">foodlist</Link>
<Link to="/food/foodmenu">foodmenu</Link>
<Switch>
<Route path="/food/foodlist" component={FoodList}>foodlist</Route>
<Route path="/food/foodmenu" component={FoodMenu}>foodmenu</Route>
</Switch>
</Fragment>
)
}
}
總之,萬變不離其宗,都是一樣的道理
2.假如說多級路由嵌套層次太深,那我們寫子級路由的path就會特別麻煩,所以我們不妨這樣搞
const Food = ({match}) => {
return (
<div>
<Link to={`${match.path}/foodmenu`}>foodmenu</Link>
<Switch>
<Route path={`${match.path}/foodmenu`} component={FoodMenu}/>
</Switch>
</div>
)
}
//在這里,match是從props解構出來的,如果你不嫌麻煩,大可以寫成this.props.match,match.path就是我們當前這個路由的路徑,有了這個,不管路由嵌套層次有多深,我們都可以通過這種方式來寫上一級的路由
2.動態路由傳參/foodList/:id,傳過去的值就在路由掛載組件的props中,props里面有個match,match中有個params,都在這里面,要注意:props只有在路由掛載的組件中才有
還可以通過/foodList?id=6這種方式傳參,傳過去的值在props中的location里面的的search中
3.編程式導航,可以在一個組件中用this.props.history.push("/path",{name:"hellow"}),來進行傳參,傳過去的值在props.location.state中
4.Route里面還有兩個屬性,render和children
-render是一個函數,語法:render={()=>{return <div></div>}},只要你的路由匹配了,這個函數才會執行
-children也是一個函數,不管匹配不匹配,這個函數都會執行
-他們兩個有個優先級關系,render的優先級總是高於children,是會覆蓋children的
<Fragment>
<h1>header</h1>
<Link to="/wiki/wikiList/">gogogo</Link>
<Route
path="/wiki/wikiList"
render={
()=>{
return <div>wikilist-children</div>
}
} //這個是只有當你路由匹配到了/wiki/wikiList才會執行
// children={() => {
// return <div>wikilist-children</div>
// }
// } //這個是只要你的路由跳到wiki了,那children就會執行
>
</Route>
</Fragment>
5.withRouter,一個典型的高階組件,如果我們既想實現點擊跳轉,又不想用Link的那個a標簽,我們可以使用withRouter給我們吐出來一個實現點擊跳轉路由的組件,代碼例子:
//使用自定義的組件:
<CustomNavLink to="/food">food</CustomNavLink>
<CustomNavLink to="/wiki">wiki</CustomNavLink>
<CustomNavLink to="/profile">profile</CustomNavLink>
//給自定義組件實現點擊功能:
const CustomNavLink = withRouter(class EnhenceCustomNavLink extends Component {
render () {
return (
<li onClick={this.goto.bind(this)}>
{
this.props.location.pathname === this.props.to ? '>' + this.props.children : this.props.children
}
</li>
)
}
goto () {
this.props.history.push(this.props.to)
}
})
//加入你的組件沒有路由信息,你可以使用withRouter(component)這樣將這個組件包起來,props里面就有路由信息了