在开发spa项目中,前端路由是一个没法绕开的技术,在整个spa前端架构中我觉的掌握前端路由配置,状态管理以及异步请求的封装是最基本的能力。本文主要介绍react-router对于react项目的做用,以及基本配置。 注:本文主要以react-router v4为基础 简单的介绍下前端
React Router 是完整的 React 路由解决方案。他知足了reactjs项目对于路由的大部分 需求,特色以下:vue
<Router routes={...}>
...
</Router>
复制代码
<Route path="/route" component={App}></Route>
复制代码
<Link to={`/users/list`} activeClassName="active">{user.name}</Link>
复制代码
import { browserHistory } from 'react-router'
browserHistory.push('/path')
复制代码
//replaceState控制路由跳转
onEnter: function (nextState, replaceState) {
replaceState(null, '...')
}
复制代码
import React from 'react'
import { Router, Route, Link } from 'react-router'
import BasicLayout from './components/BasicLayout'
React.render((
<Router>
<Route path="/" component={BasicLayout}>
<Route path="about" component={About} />
<Route path="inbox" component={Inbox}>
<Route path="children/:id" component={Children2} />
</Route>
</Route>
</Router>
), document.body)
复制代码
//基础页面组件react
const BasicLayout = React.createClass({
render() {
return (
<div>
<h1>App</h1>
<ul>
<li><Link to="/about">About</Link></li>
<li><Link to="/inbox">Inbox</Link></li>
</ul>
{this.props.children}
</div>
)
}
})
复制代码
const routes = [
{
//路由对应的路径
path: '/',
//渲染的组件
component: App,
indexRoute: { component: Dashboard },
//路由拦截
onEnter: function (nextState, replaceState) {
replaceState(null, '...')
}
// 子路由
childRoutes: [
//同父路由配置文件
{ path: 'about', component: About },
{ path: 'inbox',
component: Inbox,
childRoutes: [
//同父路由配置文件
{ path: '/messages/:id', component: Message },
{ path: 'messages/:id',
onEnter: function (nextState, replaceState) {
replaceState(null, '/messages/' + nextState.params.id)
}
}
]
}
]
}
]
React.render(<Router routes={routes} />, document.body)
复制代码
import {
BrowserRouter as Router
} from "react-router-dom";
export default function BasicExample() {
return (
<Router>
.....
</Router>
)}
复制代码
<Switch>
/
<Route exact path="/">
<Home />
</Route>
</Switch>
复制代码
<Route exact path="/">
<Home />
</Route>
复制代码
...待续vue-router
对于spa为基础的项目前端路由是必备功能之一,在react-router中v4以后和v4以后的版本差距是比较大的,若是以前没接触过react用的是vue,建议先使用v4以前的版本,由于他与vue-router的路由定义基本相同,都是集中管理,这样你上手react项目会很快。若是一直用react开发而且用的是v4以前建议尝试下v4,刚开始会很难接受,以后你会有意想不到的惊喜。api