主要组件
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传值时要是刷新页面会导致数据消失