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是公开的,显示在地址栏

      

      

    码农随笔防失忆,只为记录风雨路上的脚丫印印~
  • 相关阅读:
    angular 写 文字省略显示指令
    REACT 学习之一:普通表单过滤
    怎么能够做到实时的邮件监听-- 求指点
    C++实现Behavioral
    private virtual in c++
    接口污染
    C++ 虚函数&纯虚函数&抽象类&接口&虚基类(转)
    c++ override 关键字
    virtual function c++
    删完垃圾代码2
  • 原文地址:https://www.cnblogs.com/bella-lin/p/10026067.html
Copyright © 2011-2022 走看看