react router學習筆記

2021-08-16 17:35:40 字數 1998 閱讀 1341

一、最基本的路由配置:

**如下:

importreact ,from'react'

;importfrom'react-router'

;classcomponent

) }

}classaboutextendscomponent

}classhelloextendscomponent

) }

}classmessageextendscomponent

}react.render((

path

="/"

component

path

="/about"

component

=/>

path

="/hello"

component

=>

path

="/message/:id"

component

=/>

),document.body);

在上述**中路徑(url)與元件的對應關係為:

1、indexroute新增預設頁面

上述**中this.props.children還沒有定義,此時可以用indexroute來設定乙個預設頁面。

import

from

'react-router'

class

dashboard extends

component

}

2、路徑解耦

如果想將路徑「hello/message/:id」中的hello去掉,只需要將**:

改為:此時,使用絕對路徑代替相對路徑就可以實現。

3、相容舊的url

在做完第三步之後,訪問"/hello/message/66"將會報錯,此時我們可以使用,即在上述**之下加上:

import from "react-router";

上述**實際試講「message/:id」跳轉到「/message/:id」

二、路由匹配:

1、路徑匹配:

:paramname匹配位於"/"、"?"或者"#"之後的url

() 其內部的**是可選的

* 匹配任意字元,直到下乙個字元出現或者url的末尾

三、history

1、browserhistory

browser history 是使用 react router 的應用推薦的 history。它使用瀏覽器中的 

history

api 用於處理 url,建立乙個像example.com/some/path這樣真實的 url。**實現如下:

import from 'react-router';

2、hashhistory

hash history 使用 url 中的 hash(#)部分去建立形如example.com/#/some/path的路由.

3、creatememoryhistory

memory history 不會在位址列被操作或讀取。這就解釋了我們是如何實現伺服器渲染的。同時它也非常適合測試和其他         的渲染環境(像 react native )。

和另外兩種history的一點不同是你必須建立它,這種方式便於測試

const history=creatememoryhistory(location)

本部落格只是學習筆記,詳情參見react-router的中文文件:

React Router概述(路由)

react路由 站點 1.可以根據不同的位址,展示不同的元件 2.可以無重新整理的跳轉頁面 具備上面兩個功能的可以稱之為路由 react router 2.react router dom 利用路由核心庫,結合實際頁面,實現跟頁面路由密切相關的功能 兩種模式 協議名 schema https 主機名...

react router跳轉傳值

跳轉頁面傳遞引數 1.引入包 import from react router 2.跳轉傳值 handleclick value 3.接收值 console.info this props.location.query.title console.info this props.location.q...

React Router簡單了解(上)

g代表的是系統全域性安裝的意思 npm start預覽專案 2 使用npm 安裝react router 3 簡單的使用import react from react import reactdom from react dom reactdom.render document.getelement...