- 4是全新的版本, 和之前的版本不兼容, 浏览器和 RN 均兼容
- React 开发单页应用必备, 践行路由即组件的概念
- 核心概念: 动态路由, Route, Link, Switch
使用
npm install react-router-dom
入门组件
- BrowserRouter, 包裹整个应用
- Router 路由对应渲染的组件, 可嵌套
- Link 跳转专用
- exact 路由完全匹配
// index.js
import React from 'react'
import ReactDom from 'react-dom'
import {
createStore,
applyMiddleware,
compose
} from 'redux'
import thunk from 'redux-thunk'
import {
Provider
} from 'react-redux'
import { BrowserRouter, Link, Route } from 'react-router-dom'
import App from './App'
import {
counter
} from './index.redux'
const store = createStore(counter, compose(
applyMiddleware(thunk),
window.devToolsExtension ? window.devToolsExtension() : () => {}
))
function Erying() {
return <h2>二营</h2>
}
function Qibinglian() {
return <h2>骑兵连</h2>
}
ReactDom.render(
(<Provider store={store}>
<BrowserRouter>
<div>
<ul>
<li>
<Link to="/">一营</Link>
</li>
<li>
<Link to="/erying">二营</Link>
</li>
<li>
<Link to="/qibinglian">骑兵连</Link>
</li>
</ul>
<Route path='/' exact component={App}></Route>
<Route path='/erying' component={Erying}></Route>
<Route path='/qibinglian' component={Qibinglian}></Route>
</div>
</BrowserRouter>
</Provider>),
document.getElementById('root')
)
其他组件
- url 参数, Router组件参数可用冒号标识参数
- Redirect 组件 跳转
- Switch 只渲染一个子 Route 组件
和 redux 配合
- 复杂 redux 应用, 多个 reducer, 用 combineReducers 合并
import {combineReducers} from 'redux'
import {counter} from './index.redux'
import {auth} from './Auth.redux'
export default combineReducers({counter, auth})
网友评论