zoukankan      html  css  js  c++  java
  • 23.react-router 路由

    箭头函数扩展:

    箭头函数:

    functoin 函数名(参数){
       函数体
    }

    箭头函数:

    1、把function删掉 ,
    2、参数和{}之间加上 箭头=>

    简写:

    1、参数的简写:只有一个参数才能简写
    2、函数体的简写:只有一条语句才能简写 exp:

    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});——++用括号包起来++

    匿名函数的定义与执行:
    定义:
    (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);
     }();
     
    

    箭头函数注意事项.特性:

    1、干掉了arguments 用...args解决

    exp:

    <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:
    image

    解决方法:
    解构赋值

    <script>
    //箭头函数里面没有arguments
    var sum = (...args)=>{
        console.log(args);
    }
    sum(1,2,3,4,5);
    
    </script>
    

    res:
    image

    2、不能用箭头函数创建类 用class解决

    res:
    image

    3、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/

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

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

    Vue路由:
    1、安装

    cnpm i -S vue-router

    2、引入

    import VueRouter from "vue-router"

    3、注册成为vue插件

    Vue.use(VueRouter);

    4、创建路由对象
    let router = new VueRouter({
    	routes:[
    		{path,name,componet,componets,children}
    	]
    });
    
    5、注入到vue实例中

    new Vue({router});

    6、页面上使用路由:展现、跳转

    跳转:

    展现:

    react路由

    1、安装
    npm i -S react-router-dom

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

    3、直接使用:包含创建路由的过程


    对比:

    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

    路由传参:

    1、?         

    2、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.

    一个<Router和Android应用程序的>

    import { NativeRouter } from 'react-router-native'
    
    <NativeRouter>
      <App/>
    </NativeRouter>
    
  • 相关阅读:
    [单链表]链表指针追赶问题
    二叉查找树与平衡二叉树
    二叉树的下一个结点
    fork进程函数总结
    《Effective C++》Item2:尽量以const,enum,inline替换#define
    Hash表的使用
    [数字]整数数字的算法
    算法题:找出整数数组中两个只出现一次的数字
    删除元素的操作
    [Reprinted] 使用Spring Data Redis操作Redis(一) 很全面
  • 原文地址:https://www.cnblogs.com/zhongchao666/p/9463051.html
Copyright © 2011-2022 走看看