react router 4.x

學習React,必需要學習React router

目前 2.x和4.x均可以用,我在項目中直接安裝,默認是4.x版本,而後就踩一下。react

4.x和2.x的區別(3.x和2.x沒有區別,但2.x還在維護)react-router

  • 4.x路由再也不是集中式的,路由規則存在於佈局和組件之間。
  • 4.x的路由再也不須要嵌套來實現佈局結構和頁面(組件)嵌套。
  • 4.x沒有 props.children 來渲染組件。在4.x中<Route />組件在哪裏寫,組件就在哪裏渲染。
  • 4.x中路由規則是包容性的,也就是多個<Route />能夠同時匹配和渲染。

下面是代碼示例,(我寫在 create-react-app腳手架中)app

import React, { Component }  from 'react';

import { BrowserRouter,Route,Link,Switch} from 'react-router-dom'


class About extends Component {
    render(){
        return (
        <h1>About</h1>
        )
    }
}

class Inbox extends Component {
    render(){
        return (
        <h1>Inbox</h1>
        )
    }
}

class Home extends Component {
    render (){
        return (
        <h1>Home</h1>
        )
    }
}

const App = () => (
    <BrowserRouter>
        <div>
            <Switch>
                <Route path="/" exact component={Home} />
                <Route  path="/about" component={About} />
                <Route  path="/inbox" component={Inbox} />
                                <Redirect  to="/"  />
            </Switch>
        
            <ul>
                <li><Link to="/">Home</Link></li>
                <li><Link to="/inbox">Inbox</Link></li>
                <li><Link to="/about"> about</Link></li>
            </ul>
        </div>
    </BrowserRouter>
)
export default App;

1.BrowserRouter 表示history模式, HashRouter 表示哈希模式,這個跟其餘路由同樣,而且是做爲路由的最大容器。
2.在4.x中,全部 路由組件都必須寫在上邊提到的這兩個組件中。
3.在路由容器中,只能並列存在一個元素或組件。
4.<Switch />表示排他性路由,就是說 當前<Switch />下只有一個能匹配並渲染,這時候要注意 裏邊<Route />的書寫順序。
5.exact參數表示非包容性匹配,能夠直接理解爲嚴格匹配或徹底匹配(我本身的理解,可能不對,歡迎討論),反正這裏若是沒有exact參數 ,就只渲染 <Home />由於仍是包容性匹配,加上<Switch />和書寫順序的做用,就永遠只顯示<Home />組件),若是<Switch />也沒有的話,就是包容性匹配,好比 /about 會渲染 <Home><About>兩個組件。
6.鑑於上一條,推薦最後引入根路由匹配。
7.<Switch /> 搭配 <Redirect /> 能夠重定向, <Redirect / >必定放到最後。
8.路由模塊化,須要結合 map循環,嵌套,須要把子路由向下傳遞,傳遞時用render屬性。代碼以下dom

{
                        routes.map((value,key) =>{
                            if(value.exact){
                                return (
                                    
                                    <Route  key={key} exact path={value.path}  
                                            render={props=>( <value.component  {...props}  routes={value.routes} />) }
                                    />
                                )
                            }else{
                                return (
                                    <Route  key={key}  path={value.path}
                                        render={props=>(
                                            <value.component {...props} routes={value.routes} />
                                        )}
                                    />
                                )
                            }
                        })
                    }
相關文章
相關標籤/搜索