View on GitHub

Cycle263 Blog

Stay hungry, stay foolish.

react-router

React Router 保持 UI 与 URL 同步。它拥有简单的 API 与强大的功能例如代码缓冲加载、动态路由匹配、以及建立正确的位置过渡处理。在react-router中,URL对应Location对象,而UI是由react components来决定的,这样就转变成location与components之间的同步问题。 路由的本质,根据输入的URL地址,匹配不同的数据model并显示对应的组件。

路由流程

import React from 'react';
import { render, findDOMNode } from 'react-dom';
import { Router, Route, Link, IndexRoute, Redirect } from 'react-router';
import { createHistory, createHashHistory, useBasename } from 'history';

// 此处用于添加根路径
const history = useBasename(createHashHistory)({
  queryKey: '_key',
  basename: '/blog-app',
});

React.render((
  <Router history={history}>
    <Route path="/" component={BlogApp}>
      <IndexRoute component={SignIn}/>
      <Route path="signIn" component={SignIn}/>
      <Route path="signOut" component={SignOut}/>
      <Redirect from="/archives" to="/archives/posts"/>
      <Route onEnter={requireAuth} path="archives" component={Archives}>
        <Route path="posts" components=/>
      </Route>
      <Route path="article/:id" component={Article}/>
      <Route path="about" component={About}/>
    </Route>
  </Router>
), document.getElementById('example'));

history

history用于记录浏览器的会话历史记录,可以实现前进后退等跳转功能。在HTML5规范中,W3C规范使用pushState和replaceState方法来修改浏览器URL地址,而不触发页面重载,实际上,router的browserHistory也是类似的。