react-router-dom 配置以及使用

react-router-dom 配置以及使用

  使用React 开发应用程序,自然少不了页面路由的配置。react-rotuer-dom 作为官方提供的路由加载器自然是最好的选择方案。

目前react-router 已经更新到 4+ 版本。这里为什么推荐使用 react-router-dom ,而不使用react-router呢?在4.0 版本 以后,可以说是react-router-dom 是对react-router 更新出来的部分。提供了对dom 类操作的组件,Link 以及 BrowserRouter 。

   Link 组件,可自定义标签导航路由,该Link 标签最终被浏览器渲染成 a 标签

   BrowserRouter 而提供使用HTML5 历史 API 记录的API,这样我们就不必使用hash 导航的模式,而是HTML5 History 模式。

  在模块化开发基础上,我们将组件一一写好在对应各自的文件夹中,路由器加载组件模块时,最重要的特征是不要将每个路由中对应组件都进行加载。使用 react-loadable 是对组件懒加载的非常好的解决办法。其次我们将路由对象封装成一个数组,这样便降低了代码的复杂程度,提高页面可读性。


router.js

import Loadable from 'react-loadable'

//标记: 在定义我们的路由对象,使用react-loadable 对路由组件进行懒加载,这是经常需要做的行为。
// 详情请参考这一篇文章:https://blog.csdn.net/China_Guanq/article/details/82194928#loadable
const loadable = (filename) => Loadable({
    loader:() => import(`@/page/${filename}`),
    loading:() => ('')
});


//路由配置对象
const routers = [
    {
        path:'/view0',
        exact:true,
        component:loadable('view0')
    },
    {
        path:'/view1',
        component:loadable('view1')
    },
    {
        path:'/view2',
        component:loadable('view2')
    },
];

export default routers;

app.js

import React from 'react';
import { hot } from 'react-hot-loader'
import {
  BrowserRouter as Router,
  Route,
  Link,
  Switch,
  withRouter,
} from 'react-router-dom'

import routers from '@/router/router'

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <Router>
            <main>
              <Switch>
                  {
                      routers.map((route,index) => {
                          return(
                              <Route 
                              key={index}
                              path={route.path}
                              exact={route.exact}
                              component={route.component}/>
                          )
                      })
                  }
              </Switch>
            </main>
        </Router>
      </div>
    );
  }
}

export default hot(module)(App)

  如上示例描述如何有效的在React 工程中定义和使用路由。对于深入概念性的学习,官方文档 的参考在好不过了。
  当然这里有对react-router 实例参考教程,您可以拉取下去查看react-router 是如何工作的。 路由只是页面跳转的实现手段,因此复杂程度不高,在使用角度上来说也应“迎刃有余”。
这里写图片描述

访问地址:http://www.leileix.com/react-router-example/
github:https://github.com/RaccoonSmall/react-router-example

猜你喜欢

转载自blog.csdn.net/China_Guanq/article/details/82292023