這篇文章主要介紹react-router的配置方式有哪些,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
具體如下:
路由的概念
路由的作用就是將url和函數進行映射,在單頁面應用中路由是必不可少的部分,路由配置就是一組指令,用來告訴router如何匹配url,以及對應的函數映射,即執行對應的代碼。
react-router
每一門JS框架都會有自己定制的router框架,react-router就是react開發應用御用的路由框架,目前它的最新的官方版本為4.1.2。本文給大家介紹的是react-router相比于其他router框架更靈活的配置方式,大家可以根據自己的項目需要選擇合適的方式。
1.標簽的方式
下面我們看一個例子:
import { IndexRoute } from 'react-router' const Dashboard = React.createClass({ render() { return <div>Welcome to the app!</div> } }) React.render(( <Router> <Route path="/" component={App}> {/* 當 url 為/時渲染 Dashboard */} <IndexRoute component={Dashboard} /> <Route path="about" component={About} /> <Route path="inbox" component={Inbox}> <Route path="messages/:id" component={Message} /> </Route> </Route> </Router> ), document.body)
我們可以看到這種路由配置方式使用Route標簽,然后根據component找到對應的映射。
這里需要注意的是IndexRoute這個有點不一樣的標簽,這個的作用就是匹配'/'的路徑,因為在渲染App整個組件的時候,可能它的children還沒渲染,就已經有'/'頁面了,你可以把IndexRoute當成首頁。
嵌套路由就直接在Route的標簽中在加一個標簽,就是這么簡單
2.對象配置方式
有時候我們需要在路由跳轉之前做一些操作,比如用戶如果編輯了某個頁面信息未保存,提醒它是否離開。react-router提供了兩個hook,onLeave在所有將離開的路由觸發,從最下層的子路由到最外層的父路由,onEnter在進入路由觸發,從最外層的父路由到最下層的自路由。
讓我們看代碼:
const routeConfig = [ { path: '/', component: App, indexRoute: { component: Dashboard }, childRoutes: [ { path: 'about', component: About }, { path: 'inbox', component: Inbox, childRoutes: [ { path: '/messages/:id', component: Message }, { path: 'messages/:id', onEnter: function (nextState, replaceState) { //do something } } ] } ] } ] React.render(<Router routes={routeConfig} />, document.body)
3.按需加載的路由配置
在大型應用中,性能是一個很重要的問題,按需要加載JS是一種優化性能的方式。在React router中不僅組件是可以異步加載的,路由也是允許異步加載的。Route 可以定義 getChildRoutes,getIndexRoute 和 getComponents 這幾個函數,他們都是異步執行的,并且只有在需要的時候才會調用。
我們看一個例子:
const CourseRoute = { path: 'course/:courseId', getChildRoutes(location, callback) { require.ensure([], function (require) { callback(null, [ require('./routes/Announcements'), require('./routes/Assignments'), require('./routes/Grades'), ]) }) }, getIndexRoute(location, callback) { require.ensure([], function (require) { callback(null, require('./components/Index')) }) }, getComponents(location, callback) { require.ensure([], function (require) { callback(null, require('./components/Course')) }) } }
這種方式需要配合webpack中有實現代碼拆分功能的工具來用,其實就是把路由拆分成小代碼塊,然后按需加載。
以上是“react-router的配置方式有哪些”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。