React三种路由传值

主要组件

import React from 'react'
import {Link, Route} from 'react-router-dom'

import Detial from './Detial'


class Message extends React.Component{
  state = {
    messageArr:[
      {'id':'01',title:'消息1'},
      {'id':'02',title:'消息2'},
      {'id':'03',title:'消息3'},
    ]
  }
  render(){
    const {messageArr} = this.state
    return (
      <div>
        <h1>asd</h1>
        <ul>
          {
            messageArr.map((msgObj)=>{
              return(
                <li key={msgObj.id}>
                  {/* 向路由组件传递params参数 */}
                  {/* <Link to={'/home/message/detial/'+msgObj.id+'/'+msgObj.title}>{msgObj.title}</Link>; */}

                  {/* 向路由组件传递search参数 */}
                  {/* <Link to={'/home/message/detial/'+'?id='+msgObj.id+'&title='+msgObj.title}>{msgObj.title}</Link>; */}

                  {/* 向路由组件传递state参数 */}
                  <Link to={{pathname:'/home/message/detial',state:{id:msgObj.id,title:msgObj.title}}}>{msgObj.title}</Link>;
                </li>
              );
            })
          }
        </ul>
        <hr/>
        {/* 声明接收params参数 */}
        {/* <Route path='/home/message/detial/:id/:title' component={Detial}/> */}

        {/* search无需声明接收 */}
        {/* <Route path='/home/message/detial' component={Detial}/> */}

        {/* state无需声明接收 */}
        <Route path='/home/message/detial' component={Detial}/>
      </div>
    );
  }
}

接收路由消息组件

import React,{Component} from 'react'
import qs from 'querystring'


class Detial extends Component{
  render(){
    // 接收params参数
    // const {id,title} = this.props.match.params

    // 接收search参数
    // const {search} = this.props.location;
    // const {id,title} = qs.parse(search.slice(1));

    // 接收state参数,防止为空(页面刷新)
    const {id,title} = this.props.location.state || {};

    return(
      <ul>
        <li>{id}</li>
        <li>{title}</li>
        <li>asd</li>
      </ul>
    );
  }
}

export default Detial;

```


三种路由传值方式:params传值,search传值,state传值
使用state传值时要是刷新页面会导致数据消失


* ####1.params参数:
	* 路由链接(路径携带参数):
	* 注册路由(声明接收)
	* 接收参数
* ####2.search参数:
	* 路由链接(携带参数,?后携带参数)
	* 注册路由(无需声明,正常注册即可)
	* 接收参数:this.props.location.search
	* 备注:获取到的search是编码字符串,需要借助querystring解析
* ####3.state参数
	* 路由链接(携带参数)
	* 注册路由(无需声明,正常注册即可)
	* 接收参数:this.props.location.state
	* 备注:刷新也可以保留住参数
posted @ 2021-08-02 22:53  糖烤栗子&  阅读(151)  评论(0编辑  收藏  举报