react-router 4.X最新版本的使用 和答疑

之前收到私信很多朋友说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>
)

7.注解@withRouter

如果当前的组件并非路由组件 也就是并没有被挂载在react-router上但依然需要使用history对象那么 react-router4.X给我提供了一个注解 @withRouter

import React  from 'react';
import ReactDom from 'react-dom';
import {BrowserRouter,Route,Redirect,Switch } from 'react-router-dom';
import Login from './container/login';
import Register from './container/register';
import AuthRoute from './component/AuthRoute'
ReactDom.render(
    (<Provider store={store}>
            <BrowserRouter>
                <div className="container">
                    <AuthRoute></AuthRoute>//这个组件就用来判断用户是否有相对的权限,跳转到什么页面,但是并没有挂载在路由上 按道理来说这个组件使用不了router的history对象 但是react-router-dom 给我们提供了一个注解@withRouter 
                    <Route path='/login' component={Login}></Route>
                    <Route path='/register' component={Register}></Route>
                </div>
            </BrowserRouter>
        </Provider>
    ),
    document.getElementById("root")
)
  • 上面路由组件中的<AuthRoute></AuthRoute>组件就用来判断用户是否有相对的权限,跳转到什么页面,但是并没有挂载在路由上 按道理来说这个组件使用不了router的history对象 但是react-router-dom 给我们提供了一个注解@withRouter
//这是一个测试组件但是并未挂载在react-router上
//需求:这个组件是在所有的router
import React from 'react'
import axios from 'axios'
//导入的react-router-dom 提供的withRouter 
import {withRouter} from 'react-router-dom'
//加上这个注解之后 及时该组件未被挂载在react-router上也可以使用react-router里的对象history等
@withRouter
class AuthRoute extends React.Component{
   componentDidMount(){//conponentDidMount 组件加载完成时触发
       axios.get('/user/info')
       .then(res=>{
           if(res.status===200){
                if(res.data.code===0){

                }else{
                    如果没加这个注解你会发现答应出来的是undefind
                    console.log(this.props.history)
                }
           }
       })
   }
   constructor(props){
      super(props)  
      this.state={
          data:''
      }    
   }
   render(){
       return <p>测试组件</p>
   }
    
}
export default AuthRoute

不定档期更新 如有问题请留言 或者联系我的邮箱solitaryhao8@hotmail.com

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容