React-router的注意事項
1.入口文件index.js引入React-router
import {BrowserRouter as Router} from 'react-router-dom' ReactDOM.render(<Router><App /></Router>, document.getElementById('root'));
注意:1.路由有兩種模式 HashRouter:url中有#react
BrowserRouter:須要和後端配合編程
2.{BrowserRouter as Router} 將路由取名爲Router後端
3.組件形式讓router做用全局react-router
2.路由的使用
import {Route} from 'react-router-dom' <Route path = "/home" component = { Home } ></Route>
1.錯誤路由設置app
<Route component = {Error} ></Route>
2.重定向路由設置dom
import { Redirect} from 'react-router-dom' <Redirect from = '/' to='/home' exact ></Redirect>
3.路徑徹底匹配this
重定向用一下就行了url
<Route path = "/home" component = { Home } exact ></Route>
4.switch一次只加載一個路由spa
import {Switch} from 'react-router-dom' <Switch> <Redirect from = '/' to='/home' exact></Redirect> <Route path = "/home" component = { Home } ></Route> <Route path = "/category" component = {Category} ></Route> <Route path = "/mine" component = {Mine} ></Route> <Route path = "/list" component = {List} ></Route> <Route path = "/detail" component = {Detail} ></Route> <Route path = "/recommend" component = {Recommend} ></Route> <Route path = "/shopCar" component = {ShopCar} ></Route> <Route component = {Error} ></Route> </Switch>
5.render能夠定義一個路由模塊code
<Route path = "/detail/001" render = {()=><div>detail001</div>}></Route>
3.路由激活
import {NavLink} from 'react-router-dom' <NavLink activeClassName = 'active' to ={props.path}>
若是無需激活直接
import {Link} from 'react-router-dom'
4.render 和 children的區別
<Route path = '/mine/login' render = {()=><div>Login</div>}></Route> //不會直接顯示 <Route path = '/mine/login' children = {()=><div>Login</div>}></Route> //children 會直接顯示
5.路由link 的對象寫法
<Link to = {{ pathname: '/list/002', search: '?id=001&type=yifu', state: { num: 100, price: 200 } }}> list- 衣服 </Link>
6.動態路由
<Route path = "/list/:id" component = { List } exact></Route>
7.編程式導航
/* 編程式導航: push replace go goback */ goRecomend = () => { this.props.history.push('/recommend') } goLogin = () => { this.props.history.replace({ pathname: '/mine/login' }) } render () { return ( <HomeContainer> home <hr/> {/* 首頁跳轉推薦頁面 */} <button onClick = { this.goRecomend }> 跳轉推薦 </button> {/* 首頁跳轉登陸頁面 */} <button onClick = { this.goLogin }> 跳轉登陸 </button> </HomeContainer> ) } }
8.路由監聽
監聽整個項目,咱們要在最大的根組件中監聽App組件
app不是路由組件 沒有綁定3個屬性(history,location,match)
因此須要經過高階組件withRouter將app轉換成路由組件
import { withRouter } from 'react-router-dom' export default withRouter(App) ;