1.package引入
之前的版本中我们习惯性:
npm install react-router
版本4后,不再引入react-router,变更为:
npm install react-router-dom
目前的react-router-dom最新版本是:
4.2.2
2.Router的变更
在version3中的Router里需配置history属性,当前版本中无需配置此属性,version4提供三种不同的路由组件用来代替history属性的作用,分别是<BrowserRouter>,<HashRouter>,<MemoryRouter>
版本三:
// v3
import{Router,Route, browserHistory} from'react-router';
import routes from'./routes'
<Router history={browserHistory} routes={routes}/>
// or
<Router history={browserHistory}>
<Route path='/' component={App}>
</Route>
</Router>
版本4:
import {BrowserRouter,Route}from 'react-router-dom';
<BrowserRouter>
<div>
<Route path='/about' component={About}/>
<Route path='/contact' component={Contact}/>
</div>
</BrowserRouter>
需要注意的一点是Version4中的router组件只能有一个子元素,因此可以在route组件的最外层嵌套一个div
3.Route的变更
V3中<Route>实际上并不是一个个组件,而是路由配置对象。V4中<Route>就是真正的组件了,当基于路径去渲染一个页面时,实际上就是渲染的这个路由组件。因此当输入正确的路径时,会渲染该路由的组件,属性,子组件,当路径错误时则不会显示
/// 版本三中
<Route path='contact' component={Contact} />
// 等于
{
path: 'contact',
component: Contact
}
4.路由嵌套
在V3中通过给<Route>添加子<Route>来嵌套路由
<Route path='parent' component={Parent}>
<Route path='child' component={Child} />
<Route path='other' component={Other} />
</Route>
当输入正确的<Route>路径时,react会渲染其与其父组件,子元素将作为父元素的子属性被传递过去。就像下面这样:
<Parent {...routeProps}>
<Child {...routeProps} />
</Parent>
在V4中子<Route>可以作为父<Route>的component属性值
<Route path='parent' component={Parent} />
const Parent = () => (
<div>
<Route path='child' component={Child} />
<Route path='other' component={Other} />
</div>
)
5.on*方法的变更
react-router V3中提供的
onEnter,
onUpdate,
onLeave等方法,贯穿于react生命周期。在V4中可使用
componentDidMount或
componentWillMount来代替
onEnter,使用
componentDidUpdate 或
componentWillUpdate来代替
onUpdate,使用
componentWillUnmount来代替
onLeave。
6.新增<Switch>组件
在V3中,你可以指定很多子路由,但是只有第一个匹配的路径才会被渲染。
// v3
<Route path='/' component={App}>
<IndexRoute component={Home} />
<Route path='about' component={About} />
<Route path='contact' component={Contact} />
</Route>
V4中提供了一个相似的方法用来取代<IndexRoute>,那就是<Switch>组件,当一个<Switch>组件被渲染时,react只会渲染Switch下与当前路径匹配的第一个子<Route>
// v4
const App = () => (
<Switch>
<Route exact path='/' component={Home} />
<Route path='/about' component={About} />
<Route path='/contact' component={Contact} />
</Switch>
)