关于react.js:React-向路由组件传递参数

42次阅读

共计 1639 个字符,预计需要花费 5 分钟才能阅读完成。

咱们罕用的传递参数形式为三种,通过例子展现一下三种办法是如何应用的:

传递参数的组件

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>
    )
  }
}

正文完
 0