23.react-router 路由

箭頭函數擴展:

箭頭函數:

functoin 函數名(參數){
   函數體
}css

箭頭函數:

一、把function刪掉 ,
二、參數和{}之間加上 箭頭=>vue

簡寫:

一、參數的簡寫:只有一個參數才能簡寫
二、函數體的簡寫:只有一條語句才能簡寫 exp:node

var f = v => alert(1);

var show = (a,b)=> {
    alert(1); 
    return a +b
};

特殊:json
var show = ()=>{a:12,b:5};錯誤
var show = ()=>({a:12,b:5});——++用括號包起來++react

匿名函數的定義與執行:
定義:
(function (){
    alert(1);
});
 
執行:
1.
(function (){
    alert(1);
})();
2.
(function (){
    alert(11);
}());
 
3.
!function(){
    alert(1);
}();
4.
~function(){
    alert(1);
 }();
5.
-function(){
    alert(1);
 }();
6.
+function(){
    alert(1);
 }();

箭頭函數注意事項.特性:

一、幹掉了arguments 用...args解決

exp:android

<script>
//箭頭函數裏面沒有arguments
    
function sum1(){
    //argument
    console.log(arguments);
}
console.log(sum1(1,2,3,4,5));
var sum2 = ()=>{
    console.log(arguments);
}
console.log(sum2(1,2,3,4,5));

</script>

res:
imagegit

解決方法:
解構賦值github

<script>
//箭頭函數裏面沒有arguments
var sum = (...args)=>{
    console.log(args);
}
sum(1,2,3,4,5);

</script>

res:
imagevue-router

二、不能用箭頭函數建立類 用class解決

res:
imagenpm

三、this 指向父級
<script>
function Person(){
 
 alert(this);  
} 
var p1 = Person();//this:Window

var p2 = new Person();//this:Object

document.onclick = Person;//this:HTMLDocument
</script>

==路由==:

https://reacttraining.com/react-router/json

https://github.com/ReactTraining/react-router

http://react-china.org/t/react-router4/15843

Vue路由:
一、安裝

cnpm i -S vue-router

二、引入

import VueRouter from "vue-router"

三、註冊成爲vue插件

Vue.use(VueRouter);

四、建立路由對象
let router = new VueRouter({
    routes:[
        {path,name,componet,componets,children}
    ]
});
五、注入到vue實例中

new Vue({router});

六、頁面上使用路由:展示、跳轉

跳轉:

<router-link :to={path,query|name:params}>

展示:

react路由

一、安裝
npm i -S react-router-dom

二、引入
imoprt ReactRouter from "react-router-dom";

>三、直接使用:包含建立路由的過程

對比:

react vue
Home Home
{path:"/",name:"home",componet:Home}
exact 控制匹配到/路徑時不會再繼續向下匹配,
path 標識路由的路徑,
component 表示路徑對應顯示的組件。
HashRouter和BrowserRouter 是標籤(使用方式:包的內容只能有一個子節點) mode:"hash/history"
虛擬路徑:basename="/basename" 虛擬路徑:base:"/base"

Switch經常會用來包裹Route/Redirect,它裏面不能放其餘元素,用來只顯示一個路由

react                                               vue

<Link to="/">Home</Link>                         <router-link to="/">Home</router-link>
<Route exact path="/" component={Home} />     {path:"/",name:"home",componet:Home}
exact      控制匹配到/路徑時不會再繼續向下匹配,
path       標識路由的路徑,
component  表示路徑對應顯示的組件。

HashRouter和BrowserRouter 是標籤                   mode:"hash/history"

****使用方式:包的內容只能有一個子節點

虛擬路徑:

      basename="/basename"                        base:"/base"

Switch經常會用來包裹Route/Redirect,它裏面不能放其餘元素,用來只顯示一個路由。

exp1:
Link,Route

import React, { Component } from 'react';
import {Route,Link,Switch,Redirect} from "react-router-dom";
//import {HashRouter as Router,Route,Link,Switch,Redirect} from "react-router-dom";
const Home = ()=> <div>首頁</div>
const News = ()=> <div>新聞</div>
const Users = ()=> <div>用戶</div>
class App extends Component {
  render() {
    return (
      <div className="App">
        <a href="/home">首頁</a>
        <a href="/news">新聞</a>
        <a href="/users">用戶</a>
        <hr />
        <Link to="/home">首頁</Link>
        <Link to="/news">新聞</Link>
        <Link to="/users">用戶</Link>
        <hr />
        <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/home" component={Home}/> 
        <Route path="/news" component={News}/>
        <Route path="/users" component={Users}/>
        {/* <Route component={Home} />
        */}
        {/*<Route path="/*" component={News}/> */}
        <Redirect to="/" />
        </Switch>
      </div>
      
    );
  }
}
export default App;

exp2:
props.location:

{   
    hash:"",    
    key:"579ijl",   
    pathname:"/news",   
    search:"?id=111",       
    state:undefined     
}
mport React, { Component } from 'react';
import {BrowserRouter as Router,Route,Link,Switch,Redirect} from "react-router-dom";
const Home = (props)=> {
  console.log("Home:",props);
  return <div>首頁</div>;
};
const News = (props)=> {
  console.log("news:",props);
  return <div>新聞</div>;
};
const Users = (props)=> {
  console.log("Users:",props);
  return <div>用戶</div>;
};
const refCallback = node => {
  // `node` refers to the mounted DOM element or null when unmounted
  console.log("node",node);
  return <div>用戶函數</div>;
}

class App extends Component {
  render() {
    return (<Router>
      <div className="App">
        <Link to="/home">首頁</Link>
        <Link to="/news?id=111">新聞</Link>
        <Link to={{       
            hash:"",
            pathname:"/users",
            search:"?username=aaa&password=123",
            state:{ fromDashboard: true },
          }}>用戶</Link>
          <Link to="/refCallback" innerRef={refCallback} >用戶函數</Link> 

        <hr />
        <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/home" component={Home}/> 
        <Route path="/news" component={News}/>
        <Route path="/users" component={Users}/>
        <Route path="/refCallback" component={refCallback}/>
        <Redirect to="/"/>
        </Switch>
      </div>
      </Router>
      
    );
  }
}
export default App;

exp3:

const Users = ({match})=>{
  console.log("Users:",match);
  return <div>用戶-----{match.params.id}</div>
}
class App extends Component{
  render(){
    return (
      <div className = "App">
        <Link to="/users/111">用戶111</Link>
        <Link to="/users/222">用戶222</Link>
        <Link to="/users/333">用戶333</Link>
        <hr/>
        <Switch>
          <Route path="/users/:id" component={Users}/>
        </Switch>

      </div>
    )
  }
}

res:
image

exp4:

import React, { Component } from 'react';
import {Route,Link,NavLink,Switch,Redirect} from "react-router-dom";

const Home = ()=> <div>首頁</div>
const News = ()=> <div>新聞</div>
const Users = ()=> <div>用戶</div>

class App extends Component {
  render() {
    return (
      <div className="App">
        <Link to="/home">首頁</Link>
        <Link to="/news">新聞</Link>
        <Link to="/users">用戶</Link>
        <hr />
        <NavLink activeClassName="selected" to="/home">首頁</NavLink>  {/*點擊添加class和屬性*/}
        <NavLink activeClassName="selected" to="/news">新聞</NavLink>  
        <NavLink to="/users" activeStyle={{
          fontWeight: 'bold',
          color: 'red'
        }}>用戶</NavLink>  

        <hr />
        <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/home" component={Home}/> 
        <Route path="/news" component={News}/>
        <Route path="/users" component={Users}/>
        <Redirect to="/"/>
        </Switch>
      </div>
      
    );
  }
}
export default App;

res:
image

路由傳參:

一、?         

二、params     
  props.match.params.xxx
  props.match.path  -->"/users/:id" ----> route
  props.match.url   -->"/users/111" ----> link
exp5:

import React, { Component } from 'react';
import { Route,NavLink,Switch,Redirect} from "react-router-dom";
import "./index.css";

const Home = () =><div>首頁</div>
const News = () =><div>新聞</div>
const Users = ({match}) =>{
  console.log(111,match)
return (<div>
  <NavLink to={`${match.url}/111`} >用戶111</NavLink>
  <NavLink to={`${match.url}/222`} >用戶222</NavLink>
  <NavLink to={`${match.url}/333`} >用戶333</NavLink> 

  <Route path={`${match.url}/:id`} component={USerDetail}/>
  </div>)
}
const USerDetail = ({match}) =>{
  return (
    <div>
      <NavLink to={`${match.url}/info`}>用戶信息</NavLink>
      <NavLink to={`${match.url}/pass`}>用戶密碼</NavLink>
      <Route path={`${match.path}/info`} component={UserInfo} /> 
      <Route path={`${match.path}/pass`}  component={UserPass} />      
    </div>
  )
}
const UserInfo = ({match}) => {
  return (
    <div>
      UserInfo --- {match.url}
    </div>
  );
}
const UserPass = ({match}) => {
  return (
    <div>
      UserPass --- {match.url}
    </div>
  );
}
class App extends Component{
  render(){
    return (
      <div className = "App">
        <NavLink to="/home">首頁</NavLink>
        <NavLink to="/news">新聞</NavLink>
        <NavLink to="/users">用戶</NavLink>
        <hr/>

        <Switch>
          <Route exact path="/" component={Home}/>
          <Route path="/home" component={Home}/>
          <Route path="/news" component={News}/>
          <Route path="/users" component={Users}/>
          <Redirect to = "/" />
        </Switch>

      </div>
    )
  }
}

export default App;

res:
image

獲取數據: 都是從組件的屬性上去獲取 props
props:組成{history,location,match}
history: {go,goBack,goForward} 作跳轉用
location:{hash,pathname,search,stat}
match:{params,path,url}

exp6:

import React, { Component } from 'react';
import { BrowserRouter as Router,Route,Link,Switch,withRouter} from "react-router-dom";

function Home(){
  return <div>首頁</div>
}
function News(){
  return <div>新聞</div>
}
function Users(){
  return <div>用戶</div>
}


class App extends Component {
 
 back(){
    //window.history.back();
    //window.history.go(-1);
    console.log(this.props);
    this.props.history.go(-1);
 }
 forward(){
    //window.history.forward();
    //window.history.go(1);
    this.props.history.go(1);
 }
 push(){
   // window.location = "/"
   this.props.history.push("/");
 }


  render() {
    return ( <Router>
        <div className="App">
            <input onClick={()=> this.back()} type="button" value="back" />
            <input onClick={()=> this.forward()} type="button" value="forward" />
            <input onClick={()=> this.push()} type="button" value="回到首頁" />
            <hr />
            <Link to="/home">首頁</Link>  
            <Link to="/news">新聞</Link>  
            <Link to="/users">用戶</Link>  

            <hr />
            <Switch>
              <Route exact path="/" component={Home} /> 
              <Route path="/home" component={Home} /> 
              <Route path="/news" component={News} /> 
              <Route path="/users" component={Users} /> 
              <Route path="/*" component={News} /> 
            </Switch>

        </div>
      </Router>
    );
  }
}
export default withRouter(App);

res:
image
-----------------------------------------------------------------

withRouter: 功能 爲組件添加路由信息{history,location,match}---> this.props

運行條件: 必須在 Router下面 不能在Router外面!


** exact Switch


https://reacttraining.com/react-router/core/api/Router

1.

什麼叫 hash 地址,hash 地址就是指 # 號後面的 url。

假若有一個 Link 標籤,點擊後跳轉到 /abc/def。

BrowserRouter: http://localhost:8080/abc/def
HashRouter: http://localhost:8080/#/abc/def

若是有服務器端的動態支持,建議使用 BrowserRouter,不然建議使用 HashRouter。

緣由在於,若是是單純的靜態文件,假如路徑從 / 切換到 /a 後,此時刷新頁面,頁面將沒法正常訪問。

2.

將「URL」的歷史記錄保存在內存中(不讀取或寫入地址欄)的 <路由器> 。在測試和非瀏覽器環境(如React Native)中頗有用

3.

一個從不改變位置的

當用戶實際上沒有點擊時,這在服務器端渲染場景中頗有用,所以該位置從未實際改變。所以,名稱:static。當您只需插入一個位置並在渲染輸出上做出斷言時,它也可用於簡單的測試。

如下是一個示例節點服務器,爲 發送302狀態代碼,併爲其餘請求發送常規HTML

4.

一個

import { NativeRouter } from 'react-router-native'

<NativeRouter>
  <App/>
</NativeRouter>
相關文章
相關標籤/搜索