1. params參數(shù)
路由鏈接(傳遞參數(shù)):
<Link to={`/home/message/detail/${msgObj.id}/${msgObj.title}`}>{msgObj.title}</Link>
注冊(cè)路由(聲明接收):
<Route path="/home/message/detail/:id/:title" component={Detail}></Route>
接收參數(shù):
const {id,title}=this.props.match.params;
使用params傳遞參數(shù)地址欄的鏈接時(shí)這樣的供置;
http://localhost:3000/home/message/detail/01/消息1
2. search參數(shù)
路由鏈接(傳遞參數(shù)):
<Link to={`/home/message/detail/?id=${msgObj.id}&title=${msgObj.title}`}>{msgObj.title}</Link>
注冊(cè)路由(無(wú)需聲明伯复,正常注冊(cè)即可):
<Route path="/home/message/detail" component={Detail}></Route>
接收參數(shù):
const {search}=this.props.location;
console.log(search);//?id=01&title=消息1
const {id,title}=qs.parse(search.slice(1));//去除問(wèn)號(hào)
注意:獲取到的search是urlencoded編碼的字符串视哑,需要借助querystring解析
react庫(kù)自帶闪萄,可直接引入:import qs from "querystring";
search傳遞參數(shù)在地址欄的鏈接是這樣的:
http://localhost:3000/home/message/detail/?id=01&title=消息1
3. state參數(shù)
路由鏈接(傳遞參數(shù)):
<Link to={{pathname:"/home/message/detail",state:{id:msgObj.id,title:msgObj.title}}}>{msgObj.title}</Link>
注冊(cè)路由(無(wú)需聲明,正常注冊(cè)即可):
<Route path="/home/message/detail" component={Detail}></Route>
接收參數(shù):
const {id,title}=this.props.location.state || {};
注意:
由于傳遞的參數(shù)沒(méi)有在地址欄體現(xiàn)迹蛤,所以刷新會(huì)出錯(cuò)民珍,需要在接收參數(shù)時(shí)進(jìn)行空對(duì)象處理。
state傳遞參數(shù)不會(huì)在地址欄體現(xiàn)盗飒,地址欄是這樣的:
http://localhost:3000/home/message/detail
總結(jié):
三種傳遞參數(shù)的方式中嚷量,params用的最多,其次是search逆趣,最后是state蝶溶。
當(dāng)需要傳遞參數(shù)卻有不想展示時(shí)會(huì)使用state方式傳遞。