React Router 是完整的 React 路由解决方案
import React from 'react'
import { render } from 'react-dom'
import { browserHistory, Router, Route, IndexRoute } from 'react-router'
import App from '../components/App'
import Home from '../components/Home'
import About from '../components/About'
import Features from '../components/Features'
render(
<Router history={browserHistory}>
<Route path='/' component={App}>
<IndexRoute component={Home} />
<Route path='about' component={About} />
<Route path='features' component={Features} />
</Route>
</Router>,
document.getElementById('app')
)
标签或属性含义:
<Router>:路由总的容器
<Route>:实际的路由定义
<IndexRoute>:根路径路由定义
history:监听浏览器地址栏的变化,并将URL解析成一个地址对象,供 React Router 匹配
如果设为hashHistory,路由将通过URL的hash部分(#)切换,URL的形式类似example.com/#/path
<Router history={browserHistory}>
如果设为browserHistory,浏览器的路由就不再通过Hash完成了,而显示正常的路径example.com/path,背后调用的是浏览器的History API
<Router history={browserHistory}>
createMemoryHistory主要用于服务器渲染。它创建一个内存中的history对象,不与浏览器URL互动
const history = createMemoryHistory(location)
path:指定路由的匹配规则
component:对应加载的组件