React Router基本用法

React Router系列分为三个部分,React Router基本用法React Router从V2/V3到V4的变化React Router实现原理javascript

下面未说明的都指的是React Router V4,用到的包是react-router-domhtml

React Router的特性

路由的基本原理就是保证view和url同步,React-Router有下面一些特色java

  • 声明式的路由react

    跟react同样,咱们能够声明式的书写router,能够用JSX语法git

  • 嵌套路由及路径匹配github

  • 支持多种路由切换方式web

    能够用hashchange或者history.putStateredux

    hashChange的兼容性较好,但在浏览器地址栏显示#看上去会很丑;并且hash记录导航历史不支持location.keylocation.statehashHistoryhashChange的实现。segmentfault

    history.putState能够给咱们提供优雅的url,但须要额外的服务端配置解决路径刷新问题;browserHistoryhistory.pushState的实现。api

    由于两种方式都有优缺点,咱们能够根据本身的业务需求进行挑选,这也是为何咱们的路由配置中须要从react.router引入browserHistory并将其看成props传给Router。

React Router的包

react—router实现了路由的核心功能,在V4以前(V2,V3)可使用它,而react-router-dom基于react-router,加入了再浏览器环境下的一些功能,例如Link组件,BroswerRouter和HashRouter组件这类的DOM类组件,因此若是用到DOM绑定就使用react-router-dom,实际上react-routerreact-router-dom的子集,因此在新版本中咱们使用react-router-dom就好了,不须要使用react-router.react-router-native在React Native中用到。

react-router-redux没有集成进来

React Router的API

React-Router的API主要有

BrowserRouter HashRouter MemoryRouter StaticRouter
Link NavLink Redirect Prompt
Route Router Swith

这些组件的具体用法能够在react-router官网segmentfault一篇文章查看,这里对它们作个总结:

BrowserRouter使用HTML5提供的History api(putState,replaceState和popState事件)来保持UI和URL的同步.

HashRouter使用URL的hash部分(即window.location.hash)来保持UI和URL的同步;HashRouter主要用于支持低版本的浏览器,所以对于一些新式浏览器,咱们鼓励使用BrowserHistory

MemoryRouter将历史记录保存在内存中,这个在测试和非浏览器环境中颇有用,例如react native

StaticRouter是一个永远不会改变位置的Router,这在服务端渲染场景中很是有用,由于用户实际上没有点击,因此位置时间上没有发生变化。

NavLinkLink的区别主要在于,前者会在与URL匹配时为呈现要素添加样式属性。

Route是这些组件中重要的组件,它的任务就是在其path属性与某个location匹配时呈现一些UI。

对于Router,通常程序只会使用其中一个高阶Router,包括BrowserRouter,HashRouter,MemoryRouter,NativeRouter和StaticRouter

Switch用于渲染与路径匹配的第一个RouteRedirect

React Router基本用法—基本路由

基本操做

两个页面homedetail

//home.js
import React from 'react

export default class Home extends React.Component {
    render(){
        return (
        <div>
           <a>调转到detail页面</a>
         </div>
        )
    }
}
复制代码
//detail.js
import React from 'react'

export default class Home extends React.Component {
    render(){
        return(
        <div> <a>跳转到home页面</a> </div>
        )
    }
}
复制代码
//Route.js
import React from 'react'
import {HashRouter, Route, Switch} from 'react-router-dom'
import Home from '../home'
import Detail from '../detail'

const BasicRoute = () => (
<HashRouter>
     <Switch>
       <Route exact path='/' component={Home} />
       <Route exact path='/detail' component={Detail} />
      </Switch>
 </HashRouter>
)

export default BasicRoute;
复制代码
//index.js
import React from 'react'
import ReactDOM from 'react-dom'
import Router from './router/router'

ReactDOM.render(
<Router/>,
document.getElementById('root')
)
复制代码

经过a标签跳转

修改home.jsdetail.js

//home.js
import React from 'react'

export default class Home extends React.Component {
    render(){
        return(
        <div> <a href='#/detail'>跳转到detail页面</a> </div>
        )
    }
}
复制代码
//detail.js
import React from 'react';


export default class Home extends React.Component {
    render() {
        return (
            <div> <a href='#/'>回到home</a> </div>
        )
    }
}
复制代码

经过函数跳转

首先须要修改router.js中的代码

...
import {HashRouter, Route, Switch, hashHistory} from 'react-router-dom';
...
<HashRouter history={hashHistory}>
...
复制代码

而后在home.js

export default class Home extends React.Component {
    constructor(props) {
        super(props);
    }
    
    render() {
        return (
            <div> <a href='#/detail'>去detail</a> <button onClick={() => this.props.history.push('detail')}>经过函数跳转</button> </div>
        )
    }
}
复制代码

传参

不少场景下,咱们还须要在页面跳转的同时传递参数,在react-router-dom中,一样提供了两种方式进行传参:

url传参和经过push函数隐式传参

url传参

修改route.js中的代码

...
<Route exact path="/detail/:id" component={Detail}/>
...
复制代码

而后修改detail.js,使用this.props.match.params来获取url传过来的参数

...
componentDidMount() {
    console.log(this.props.match.params);
}
...
复制代码

在地址栏输入“http://localhost:3000/#/detail/3”,打开控制台:

img

隐式传参

修改home.js

import React from 'react';

export default class Home extends React.Component {
    constructor(props) {
        super(props);
    }
    
    render() {
        return (
            <div> <a href='#/detail/3'>去detail</a> <button onClick={() => this.props.history.push({ pathname: '/detail', state: { id: 3 } })}>经过函数跳转</button> </div>
        )
    }
}
复制代码

在detai.js中,就可使用this.props.location.state获取home传过来的参数

componentDidMount() {
    //console.log(this.props.match.params);
    console.log(this.props.history.location.state);
}
复制代码

跳转后打开控制台能够看到参数被打印:

img

其余函数

replace

有些场景下,重复使用push或a标签跳转会产生死循环,为了不这种状况出现,react-router-dom提供了replace。在可能会出现死循环的地方使用replace来跳转:

this.props.history.replace('/detail');
复制代码
goBack

场景中须要返回上级页面的时候使用:

this.props.history.goBack();
复制代码

React Router的基本用法—动态路由

React Router V4 实现了动态路由。

对于大型应用来讲,一个首当其冲的问题就是所需加载的JavaScript的大小。程序应当只加载当前渲染页所需的JavaScript。有些开发者将这种方式称之为“代码分拆” —— 将全部的代码分拆成多个小包,在用户浏览过程当中按需加载。React-Router 里的路径匹配以及组件加载都是异步完成的,不只容许你延迟加载组件,而且能够延迟加载路由配置。Route能够定义 getChildRoutes,getIndexRoute 和 getComponents 这几个函数。它们都是异步执行,而且只有在须要时才被调用。咱们将这种方式称之为 “逐渐匹配”。 React-Router 会逐渐的匹配 URL 并只加载该URL对应页面所需的路径配置和组件。

const CourseRoute = {
  path: 'course/:courseId',

  getChildRoutes(location, callback) {
    require.ensure([], function (require) {
      callback(null, [
        require('./routes/Announcements'),
        require('./routes/Assignments'),
        require('./routes/Grades'),
      ])
    })
  },

  getIndexRoute(location, callback) {
    require.ensure([], function (require) {
      callback(null, require('./components/Index'))
    })
  },

  getComponents(location, callback) {
    require.ensure([], function (require) {
      callback(null, require('./components/Course'))
    })
  }
}

复制代码

React Router的基本用法—嵌套路由

若是咱们给/,/category/products建立了路由,但若是咱们想要/category/shoes,/category/boots,/category/footwear这种形式的url呢?在React Router V4以前的版本中,咱们的作法是利用Route组件的上下层嵌套:

<Route exact path="/" component={Home}/>
 <Route path="/category" component={Category}/>
   		<Route path='/category/shoes' component={Shoes}/>
   		<Route path='/category/boots' component={Boots}/>
   		<Route path='/category/footwear' component={Footwear}/>
 <Route path="/products" component={Products}/>
   
复制代码

那么在V4版本中该怎么实现嵌套路由呢,咱们能够将嵌套的路由放在父元素里面定义。

//app.js
import React, { Component } from 'react';
import { Link, Route, Switch } from 'react-router-dom
import Category from './Category'

class App extends Component {
    render(){
        return(
         <div>
        <nav className="navbar navbar-light">
          <ul className="nav navbar-nav">
            <li><Link to="/">Homes</Link></li>
            <li><Link to="/category">Category</Link></li>
            <li><Link to="/products">Products</Link></li>
          </ul>
       </nav>
 
    <Switch>
      <Route exact path="/" component={Home}/>
      <Route path="/category" component={Category}/>
      <Route path="/products" component={Products}/>
    </Switch>
    </div>
        )
    }
}

export default App;
复制代码
//Category.jsx

import React from 'react';
import { Link, Route } from 'react-router-dom';
 
const Category = ({ match }) => {
return( <div> <ul> <li><Link to={`${match.url}/shoes`}>Shoes</Link></li> <li><Link to={`${match.url}/boots`}>Boots</Link></li> <li><Link to={`${match.url}/footwear`}>Footwear</Link></li> </ul> <Route path={`${match.path}/:name`} render= {({match}) =>( <div> <h3> {match.params.name} </h3></div>)}/> //嵌套路由 </div>) } export default Category; 复制代码

咱们须要理解上面的match对象,当路由路径和当前路径成功匹配时会产生match对象,它有以下属性:

  • match.url: 返回路由路径字符串,经常使用来构建Link路径
  • match.path: 返回路由路径字符串,经常使用来构建Route路径
  • match.isExact: 返回布尔值,若是准确(没有任何多余字符)匹配则返回true
  • match.params: 返回一个对象包含Path-to-RegExp包从URL解析测键值对

注意match.urlmatch.path没有太大区别,控制台常常出现相同的输出,例如访问/user

const UserSubLayout = ({ match }) => {
  console.log(match.url)   // output: "/user"
  console.log(match.path)  // output: "/user"
  return (
    <div className="user-sub-layout">
      <aside>
        <UserNav />
      </aside>
      <div className="primary-content">
        <Switch>
          <Route path={match.path} exact component={BrowseUsersPage} />
          <Route path={`${match.path}/:userId`} component={UserProfilePage} />
        </Switch>
      </div>
    </div>
  )
}
//注意这里match在组件的参数中被解构,意思就是咱们可使用match.path代替props.match.path
复制代码

通常的,咱们在构建Link组件的路径时用match.url,在构建Route组件的路径时用match.path

还有一个地方须要理解的是Route组件有三个能够用来定义要渲染内容的props:

  • component: 当URL匹配时,router会将传递的组件使用React.createElement来生成一个React元素
  • **render:**适合行内渲染,在当前路径匹配路由路径时,renderprop指望一个函数返回一个元素
  • children: childrenproprender很相似,也指望一个函数返回一个React元素。然而,无论路径是否匹配,children都会渲染。

React Router的基本用法—带path参数的嵌套路由

一个真实的路由应该是根据数据,而后动态显示。假设咱们获取了从服务端API返回的product数据,以下所示

//Product.jsx

const productData = [
{
  id: 1,
  name: 'NIKE Liteforce Blue Sneakers',
  description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin molestie.',
  status: 'Available'
 
},
{
  id: 2,
  name: 'Stylised Flip Flops and Slippers',
  description: 'Mauris finibus, massa eu tempor volutpat, magna dolor euismod dolor.',
  status: 'Out of Stock'
 
},
{
  id: 3,
  name: 'ADIDAS Adispree Running Shoes',
  description: 'Maecenas condimentum porttitor auctor. Maecenas viverra fringilla felis, eu pretium.',
  status: 'Available'
},
{
  id: 4,
  name: 'ADIDAS Mid Sneakers',
  description: 'Ut hendrerit venenatis lacus, vel lacinia ipsum fermentum vel. Cras.',
  status: 'Out of Stock'
},
 
];
复制代码

咱们须要根据下面这些路径建立路由:

  • /products. 这个路径应该展现产品列表。
  • /products/:productId.若是产品有:productId,这个页面应该展现该产品的数据,若是没有,就该展现一个错误信息。
//Products.jsx

const Products = ({ match }) => {
 
   const productsData = [
    {
        id: 1,
        name: 'NIKE Liteforce Blue Sneakers',
        description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin molestie.',
        status: 'Available'
 
    },
 
    //Rest of the data has been left out for code brevity
 
];
 /* Create an array of `<li>` items for each product*/
  var linkList = productsData.map( (product) => {
    return(
      <li> <Link to={`${match.url}/${product.id}`}> {product.name} </Link> </li>
      )
 
    })
 
  return(
    <div>
        <div>
         <div>
           <h3> Products</h3>
           <ul> {linkList} </ul>
         </div>
        </div>
 
        <Route path={`${match.url}/:productId`}
            render={ (props) => <Product data= {productsData} {...props} />}/>
        <Route exact path={match.url}
            render={() => (
            <div>Please select a product.</div>
            )}
        />
    </div>
  )
}
复制代码

下面是Product组件的代码

//Product.jsx

const Product = ({match,data}) => {
  var product= data.find(p => p.id == match.params.productId);
  var productData;
 
  if(product)
    productData = <div> <h3> {product.name} </h3> <p>{product.description}</p> <hr/> <h4>{product.status}</h4> </div>;
  else
    productData = <h2> Sorry. Product doesnt exist </h2>;
 
  return (
    <div> <div> {productData} </div> </div>
  )
}
复制代码

React Router的基本用法—保护式路由

考虑到这样一个场景,用户必须先验证登陆状态才能进入到主页,因此须要保护式路由,这里须要保护的路由是Admin,若是登陆没经过则先进入Login路由组件。保护式路由会用到重定向组件Redirect,若是有人已经注销了帐户,想进入/admin页面,他们会被重定向到/login页面。当前路径的信息是经过state传递的,若用户信息验证成功,用户会被重定向回初始路径。在子组件中,你能够经过this.props.location.state获取state的信息。

`<Redirect to={{pathname: '/login', state: {from: props.location}}} />`
复制代码

具体地,咱们须要自定义路由来实现上面的场景

class App5 extends React.Component {
    render(){
        return (
            <div className="app5">
                <ul>
                    <li>
                        <Link to='/'>Home</Link>
                    </li>
                    <li>
                        <Link to='/category'>Category</Link>
                    </li>
                    <li>
                        <Link to='/products'>Products</Link>
                    </li>
                    <li>
                        <Link to='/admin'>Admin</Link>
                    </li>
                </ul>
                <Route exact path='/' component={Home} />
                <Route path='/category' component={Category} />
                <Route path='/products' component={Products} />
                <Route path='/login' component={Login} />

                {/*自定义路由*/}
                <PrivateRoute path='/admin' component={Admin} />
            </div>
        )
    }
}

const Home = props => <h2>This is Home {console.log('Home-Props')}{console.log(props)}</h2>

const Admin = () => <h2>Welcome to admin!</h2>


// 自定义路由
const PrivateRoute = (({component:Component,...rest}) => {
    return (
        <Route
            {...rest}
            render={props =>
                // 若是登陆验证经过则进入Admin路由组件
                fakeAuth.isAuthenticated === true
                ?(<Component />)
                // 将from设置为Admin路由pathname,并传递给子组件Login
                :(<Redirect to={{pathname:'/login',state:{from:props.location.pathname}}} />)
            }
         />
    )
})
复制代码

Login组件实现以下,主要就是经过this.props.location.state.from来记住是从哪一个页面跳转过来的,而后若是toAdminfalse的话就要进行登陆,登陆后将toAdmin设为true,为true就是进行重定向跳转到原来的页面<Redirect to={from} />

class Login extends React.Component {
    constructor(){
        super()
        this.state = {
            toAdmin:false
        }
    }

    login = () =>{
        fakeAuth.authenticate(() => {
            this.setState({
                toAdmin:true
            })
        })
    }

    render(){
        const from = this.props.location.state.from
        const toAdmin = this.state.toAdmin
        if(toAdmin) {
            return (
                <Redirect to={from} /> ) } return ( <div className="login"> {console.log(this.props)} <p>You must log in then go to the{from} </p> <button onClick={this.login}> Log in </button> </div> ) } } export default Login export const fakeAuth = { // 验证状态 isAuthenticated:false, authenticate(cb){ this.isAuthenticated = true setTimeout(cb,100) } } 复制代码

参考文章:

深刻理解React-Router路由原理

React Router中文文档

React Router英文文档

React Router API介绍

React Router V4版本 彻底指北

React保护式路由

相关文章
相关标签/搜索