在開發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