我们常用的传递参数方式为三种,通过例子展示一下三种方法是如何使用的:

传递参数的组件

import React, { Component } from 'react'
import { Switch,Route,Link } from 'react-router-dom'
import Detail from './Detail'

export default class Message extends Component {
  state ={
    messageArr :[
      {id:'01',title:'消息1'},
      {id:'02',title:'消息2'},
      {id:'03',title:'消息3'}
    ]
  }
  render() {
    const {messageArr} = this.state
    return (
      <div>
        <ul>
          {
            messageArr.map((msgObj) =>{
              return (
                <li key={msgObj.id}>
                  {/* 向路由组件传递 params 参数 */}
                  {/* <Link to={`/home/message/detail/${msgObj.id}/${msgObj.title}`}>{msgObj.title}</Link> */}
                  {/* 向路由组件传递 search 参数 */}
                  {/* <Link to={`/home/message/detail/?id=${msgObj.id}&title=${msgObj.title}`}>{msgObj.title}</Link> */}

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

          {/* search 参数无需声明接收 */}
          {/* <Route path='/home/message/detail' component={Detail}></Route> */}

          {/* state 参数无需声明接收 */}
          <Route path='/home/message/detail' component={Detail}></Route>
        </Switch>
      </div>
    )
  }
}

接收参数的组件

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

const detailData = [
  {id:'01',content:'你好,中国'},
  {id:'02',content:'你好,上海'},
  {id:'03',content:'你好,北京'}
]

export default class Detail 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

    // 查找对应id 的 content
    const findResult = detailData.find((detailObj)=>{
      return detailObj.id === id
    })
    return (
      <div>
          <li>ID:{id}</li>
          <li>Title:{title}</li>
          <li>Content:{findResult.content}</li>
      </div>
    )
  }
}
03-05 20:05