【重点突破】—— React Router 4:全新的React组件式的动态路由库

前言:正在学习react大众点评项目课程的todoList应用阶段,学习react、redux、react-router基础知识。


一、客户端路由和服务端路由

 

 

二、React Router相关库

  • react-router
  • react-router-dom(直接使用)
  • react-router-native

1.<Router>

<BrowserRouter>

<HashRouter>

//src->app.js

import React, { Component } from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import Home from "./Home";
import About from "./About";
import Contact from "./Contact";
import Nav from "./Nav";

class App extends Component {
  render() {
    return (
      <Router>
        <div>
          <Nav />
          <Switch>
             <Route path="/about" component={About} />
             <Route path="/contact" component={Contact} />
             <Route path="/" exact component={Home} />   //兜底组件
          </Switch>
        </div>
      </Router>
    );
  }
}

export default App;

2.<BrowserRouter>

HTML5 history API(pushState, replaceState)

需要Web服务器额外配置

3.<HashRouter>

使用url的hash部分作为路由信息

主要为了兼容老版本浏览器

 

三、路由配置:Route  

  • path
  • match
    //src->app.js
    <Route path="/user/:user" component={User} /> 
    
    //src->User.js
    import React, { Component } from 'react'
    
      class User extends Component {
         render() {
            const { match } = this.props
            return (
              <div>
                User: {match.params.user}
              </div>
            );
         }
      }
    
      export default User;
    

       

 

四、路由匹配  

默认情况下,react Router中每一个Route都会和应用的url地址进行匹配

  • exact:url和path完全相同的情况下,Route才会被匹配成功
  • <Switch>:只会去匹配第一个被匹配到的Route

 

五、路由渲染组件的方式

<Route component>

<Route path="/" exact component={Home} />

<Route path="/" exact component={() => <Home/>} />

缺点:每次调用时都会重新渲染一个组件

<Route render>

<Route path="/about" render={(props) => </About {...props}/>} />

<Route children>  

<Route
    path="/contact"
    children={props => <div>{props.match ?
    "active" : "inactive"}</div>}
/>

可以根据是否匹配成功,显示出不同的内容 

 

六、React Router 4 全新思维  

  • 一切皆组件
  • 动态路由的离散式声明方式:不再需要集中在某一个文件内显示
//src->app.js

<Route path="/user" component={User} />
//src->User.js
import React, { Component } from 'react';
import {Route} from 'react-router-dom'
import UserDetail from './UserDetail'

class User extends Component {
  render() {
    const {match} = this.props
    return (
      <div>
        <Route path={`${match.path}/:user`} component={UserDetail} />
      </div>
    );
  }
}

export default User; 
//src->UserDetail.js
import React, { Component } from 'react';

class UserDetail extends Component {
  render() {
    const {match} = this.props
    return (
      <div>
        UserDetail: {match.params.user}
      </div>
    );
  }
}

export default UserDetail; 

  


 注:项目来自慕课网

posted @ 2021-02-06 18:20  柳洁琼Elena  阅读(215)  评论(0编辑  收藏  举报