react-router-dom路由switch使用

使用React構建的單頁面應用,要想實現頁面間的跳轉,首先想到的就是使用路由。在React中,經常使用的有兩個包能夠實現這個需求,那就是react-router和react-router-dom。本文主要針對react-router-dom進行說明。javascript

 

 <Switch>是惟一的由於它僅僅只會渲染一個路徑。相比之下(不使用<Switch>包裹的狀況下),每個被location匹配到的<Route>將都會被渲染。java

安裝

首先進入項目目錄,使用npm安裝react-router-dom:react

npm install react-router-dom --save-dev //這裏能夠使用cnpm代替npm命令

基本操做

而後咱們新建兩個頁面,分別命名爲「home」和「detail」。在頁面中編寫以下代碼:npm

import React from 'react'; export default class Home extends React.Component { render() { return ( <div>
                <a>去detail</a>
            </div> ) } }

 

home.jsreact-router

import React from 'react'; 
export default class Home extends React.Component { render() { return ( <div>
                <a>回到home</a>
            </div> ) } }

 

detail.jsdom

而後再新建一個路由組件,命名爲「Router.js」,並編寫以下代碼:spa

import React from 'react'; import {HashRouter, Route, Switch} from 'react-router-dom'; import Home from '../home'; import Detail from '../detail'; const BasicRoute = () => ( <HashRouter>
        <Switch>
            <Route exact path="/" component={Home}/>
            <Route exact path="/detail" component={Detail}/>
        </Switch>
    </HashRouter> );
export default BasicRoute;
 

 

 
   

如上代碼定義了一個純路由組件,將兩個頁面組件Home和Detail使用Route組件包裹,外面套用Switch做路由匹配,當路由組件檢測到地址欄與Route的path匹配時,就會自動加載響應的頁面。code

 

而後在入口文件中——我這裏指定的是index.js——編寫以下代碼:component

import React from 'react'; import ReactDOM from 'react-dom'; import Router from './router/router'; ReactDOM.render( <Router/>, document.getElementById('root') );

 

這裏至關於向頁面返回了一個路由組件。咱們先運行項目看一下效果,在地址欄輸入「 http://localhost:3000/#/」:


 

 輸入「 http://localhost:3000/#/detail」:

 

若是不使用 switch router

兩個組件都打印

相關文章
相關標籤/搜索