react-router 使用

  1. react-router&&react-router-dom的区别
    //写法一
    import {Switch, Route, Router} from 'react-router';
    import {BrowserRouter, Link} from 'react-router-dom';
    
    //写法二
    import {Swtich, Route, Router, BrowserRouter, Link} from 'react-router-dom';

    react-router提供路由的核心功能,react-router-dom是依赖于react-router的进一步功能扩充,增加了Link组件和BrowserRouter组件等。所以我们在安装了react-router-dom的情况下不需要再显示的安装react-router。

  2. react-router的原理:框架去拦截浏览器跳转,自己去同步UI组件
  3. Router:是一个容器组件,真正的路由需要通过Route去定义。
    import { Router, Route, hashHistory } from 'react-router';
    
    render((
      <Router history={hashHistory}>
        <Route path="/" component={App}/>
      </Router>
    ), document.getElementById('app'));

    参数:history--->值为hashHistory代表路由的切换由url的hash变化决定,即#后面的部分;browserHistory调用浏览器的history API,需要后端配合;createMemoryHistory用于服务端渲染,创建一个内存中的history对象(虚拟的)

  4. 在4.0版本中 直接使用<BrowserRouter>,<HashRouter>,<MemoryRouter>来代替制定history参数的router组件
  5. 嵌套路由,会首先加载外层组件 再加载内层组件
    <Router history={hashHistory}>
      <Route path="/" component={App}>
        <Route path="/repos" component={Repos}/>
        <Route path="/about" component={About}/>
      </Route>
    </Router>

    注意内层组件是作为this.props.children传给外层组件的,所以我们的app组件需要写成:

    <div>
          {this.props.children}
    </div>
  6. route组件:参数 path--->匹配路由的路径, exact--->精确匹配,component--->渲染的组件
  7. IndexRoute:指定默认的组件;Redirectc 重定向组件;IndexRedirect 默认重定向组件(当没有route匹配的时候)
    <Route path="inbox" component={Inbox}>
      {/* 从 /inbox/messages/:id 跳转到 /messages/:id */}
      <Redirect from="messages/:id" to="/messages/:id" />
    </Route>
    <Route path="/" component={App}>
      <IndexRedirect to="/welcome" />
      <Route path="welcome" component={Welcome} />
      <Route path="about" component={About} />
    </Route>
  8. switch组件:确保只渲染第一个匹配的路径
  9. Link组件
    <Link to="/about">{About}</Link>
  10. jjj

猜你喜欢

转载自www.cnblogs.com/longlongdan/p/11304568.html