本文介紹關于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找到對應的映射。
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中有實現代碼拆分功能的工具來用,其實就是把路由拆分成小代碼塊,然后按需加載。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答