• React v5向路由组件传参


    1.params参数

    路由链接(携带参数):

    <Link to={`/home/message/details/${msgObj.id}/${msgObj.title}`}>{msgObj.title}</Link>
    
    • 1

    注册路由(声明接收):

    <Route path={"/home/message/details/:id/:title"}  component={Detail}></Route>
    
    • 1

    接收参数:

    const {id,title} = this.props.match.params
    
    • 1

    2.search参数

    路由链接(携带参数):

    <Link to={`/home/message/details?id=${msgObj.id}&title=${msgObj.title}`}>{msgObj.title}</Link>
    
    • 1

    注册路由(无需声明,正常注册即可):

    <Route path={"/home/message/details"}  component={Detail}></Route>
    
    • 1

    接收参数:获取到search参数是urlencode编码字符串,需要借助querystring解析,vscode提示我用querystring-es3,我就安装dev开发依赖yarn add -D querystring-es3,再import引入,解析后的对象,首个key多了?,用slice函数进行截取

    const {id,title} = qs.parse(this.props.location.search.slice(1))
    
    • 1

    3.state参数

    路由链接(携带参数):to值为对象,当中需要的key有pathname和state

    <Link to={{pathname:'/home/message/details',state:{id:msgObj.id,title:msgObj.title}}}>{msgObj.title}</Link>
    
    • 1

    注册路由(无需声明,正常注册即可):

    <Route path={"/home/message/details"}  component={Detail}></Route>
    
    • 1

    接收参数:刷新也可以保住参数,利用|| {}保证清空缓存后不会出现state值为undefined的bug

    const {id,title} = this.props.location.state  || {}
    
    • 1

    备注:
    根据id查找数据,用数组的find方法

    const findResult = DetailData.find((detailObj) => {
         return detailObj.id === id
     }) || {}
    
    • 1
    • 2
    • 3

    4.replace和push编程式路由导航

    1. replace跳转 + 携带params参数

      触发回调函数(记得要用函数柯里化,因为传了参数id title)

      this.props.history.replace(`/home/message/details/${id}/${title}`)
      
      • 1

      push同理

    2. replace跳转 + 携带search参数

      触发回调函数(记得要用函数柯里化,因为传了参数id title)

      this.props.history.replace(`/home/message/details?id=${id}&title=${title}`)
      
      • 1

      push同理

    3. push跳转 + 携带state参数(replace和push函数可携带路径参数和state参数)

      触发回调函数(记得要用函数柯里化,因为传了参数id title)

      this.props.history.push(`/home/message/details`,{id,title})
      
      • 1

      push同理

      注意:同时也要记得展示区时,声明参数的接受,params参数需要在注册路由时声明接收params参数,search和state参数正常注册即可,无需声明;还要注意接收参数的组件的接收参数方式。具体参考1、2、3

  • 相关阅读:
    std::true_type和std::false_type
    【Vue】深究计算和侦听属性的原理
    Linux发布Spring Boot项目
    国外问卷调查赚钱靠谱吗?
    分布式开发-文件上传到文件服务器
    石油化工行业中低压电动机回路抗晃电解决方案
    八大基本排序(详解)
    Web3 solidity编写cancelorder取消订单函数 并梳理讲述逻辑
    LabelImg使用笔记
    Android Jetpack Compose之生命周期与副作用
  • 原文地址:https://blog.csdn.net/qq_44850230/article/details/125418832