React路由-進階篇
路由進階
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裡面就有路由資訊了