zoukankan      html  css  js  c++  java
  • React成长路之踩坑路:react-router4路由传参(@react-router4.3.1)

    在react-router@4中传参有三种方式

    一、通过params传参:

      1、在路由表中:

    <Route path="/search/:type/:keyword?" component={Search} />

      2、Link处使用:

    <Link to={'/detail/' + data.id}>

      3、js处使用

    this.props.history.push('/detail/' + id)    //页面跳转
    this.props.history.replace('/detail/' + id)   //参数改变重新当前页面渲染

      4、参数获取

    console.log(this.props.match.params)

    这种方法有两个注意点,与2、3区别:

      11、<Route path="/search/:type(/:keyword)" component={Search} />   //23路由的可选参数keyword

        <Route path="/search/:type/:keyword?" component={Search} />   // 4路由可选参数是这样的

      12、this.props.history.push('/detail/' + id)    //2/3中可实现页面的反复渲染,在4中就会报错,用该用replace代替

      13、this.props.params    //在2/3可获取到传递过来的参数,而在4中会抱undefined的错会,改用this.props.match.params即可

    二、通过query传参

      1、Link处使用:

    <Link to={{pathname:'/detail/',query:{'id': data.id} }}>

      2、js处引用:

    this.props.history.push({pathname:'/search', query:{'type': type,'keyword': value}})

      3、参数获取:

    console.log(this.props.location.query) //获取到传递过来的query对象

    三、通过state传参

      1、Link处使用

    <Link to={{pathname:'/detail/',query:{'id': data.id} }}>

      2、js处引用

    this.props.history.push({pathname:'/search', query:{'type': type,'keyword': value}})

      3、参数获取

    console.log(this.props.location.state) //获取到传递过来的query对象

    注:query与state传参异同点

      同:

      1、不需要配置路由表

      2、必须有其它页面跳转过来才能获取参数,当前页面刷新,参数清空

      异:

      1、state传参是加密的,query是公开的,显示在地址栏

      

      

    码农随笔防失忆,只为记录风雨路上的脚丫印印~
  • 相关阅读:
    leetcode-26-删除排序数组中的重复项
    用设计模式优化if else
    Builder设计模式
    退役划水(6)
    linux下安装nginx
    .NET 云原生架构师训练营(模块二 基础巩固 引入)--学习笔记
    SpringBoot项目的jar包瘦身计划
    如何解决高并发秒杀的超卖问题
    idea 最新jar包
    ArcGIS10.2企业数据库安装与配置
  • 原文地址:https://www.cnblogs.com/bella-lin/p/10026067.html
Copyright © 2011-2022 走看看