关于javascript:React-向路由组件传递-search-参数

72次阅读

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

传递参数组件的 jsx 文件:

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>
                </li>
              ) 
            })
          }
        </ul>
        <hr/>
        {/* 注册路由 */}
        <Switch>
          {/* 申明接管 params */}
          {/* <Route path='/home/message/detail/:id/:title' component={Detail}></Route> */}
          
          {/* search 参数无需申明接管 */}
          <Route path='/home/message/detail' component={Detail}></Route>
        </Switch>
      </div>
    )
  }
}

接管参数组件的 jsx 文件:

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

    // 查找对应 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