前端成神之路react

react react-router 4.2.2 最新版

2018-05-27  本文已影响185人  吴佳浩

之前收到私信很多朋友说react当中的router使用经常报错。现在总结一下 使用的常规操作希望对你的学习带来一点帮助

1.package引入

之前的版本中我们习惯性:npm install react-router
版本4后,不再引入react-router,变更为:npm install react-router-dom
目前的react-router-dom最新版本是:4.2.2

2.Router的变更

在3.x版本中的Router里需配置history属性,当前版本中无需配置此属性,4.x版本中提供三种不同的路由组件用来代替history属性的作用,分别是<BrowserRouter>,<HashRouter>,<MemoryRouter>

//3.x版本引入
    import{Router,Route, browserHistory} from'react-router';
    import routes from'./routes'
    <Router history={browserHistory} routes={routes} />
// 或者
        <Router history={browserHistory}>
            <Route path='/' component={App}>
            </Route>
        </Router>

//4.2.2版本

import {BrowserRouter,Route}from 'react-router-dom'; 
<BrowserRouter> 
  <div> 
       <Route path='/about' component={About}/> 
       <Route path='/contact' component={Contact}/> 
 </div> 
</BrowserRouter>
//需要注意的一点是V4中的router组件只能有一个子元素,因此可以在route组件的最外层嵌套一个div

//3.X版本 Route的变更

3.X版本中<Route>实际上并不是一个个组件,而是路由配置对象。
4.x版本中<Route>就是真正的组件了,当基于路径去渲染一个页面时,
实际上就是渲染的这个路由组件。因此当输入正确的路径时,会渲染该路由的组件,
属性,子组件,当路径错误时则不会显示

//在3.x版本中的的元素
<Route path='contact' component={Contact} />
// 相当于
{
  path: 'contact',
  component: Contact
}

4.路由嵌套

在3.x版本中中通过给<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>

在4.x版本中子<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 3.x版本中提供的onEnter,onUpdate,onLeave等方法,贯穿于react生命周期。

在4.x版本中可
使用componentDidMount或componentWillMount来代替onEnter,
使用componentDidUpdate 或 componentWillUpdate来代替onUpdate,
使用componentWillUnmount来代替onLeave。

6.新增<Switch>组件

在3.x版本中,你可以指定很多子路由,但是只有第一个匹配的路径才会被渲染。

// 3.x版本
<Route path='/' component={App}>
  <IndexRoute component={Home} />
  <Route path='about' component={About} />
  <Route path='contact' component={Contact} />
</Route>

4.x版本中提供了一个相似的方法用来取代<IndexRoute>,那就是<Switch>组件,当一个<Switch>组件被渲染时,react只会渲染Switch下与当前路径匹配的第一个子<Route>

// 4.x版本
const App = () => (
 <Switch>
   <Route exact path='/' component={Home} />
   <Route path='/about' component={About} />
   <Route path='/contact' component={Contact} />
 </Switch>
)
上一篇 下一篇

猜你喜欢

热点阅读