一、向路由組件傳遞參數
1.params參數
2.search參數
3.state參數
二、編程式路由導航
三、BrowserRouter與HashRouter的區別
四、代碼
1. 傳遞參數
1 import React, { Component } from 'react' 2 import {Link,Route} from 'react-router-dom' 3 import Detail from './Detail' 4 5 export default class Message extends Component { 6 state = { 7 messageArr:[ 8 {id:'01',title:'消息1'}, 9 {id:'02',title:'消息2'}, 10 {id:'03',title:'消息3'}, 11 ] 12 } 13 render() { 14 const {messageArr} = this.state 15 return ( 16 <div> 17 <ul> 18 { 19 messageArr.map((msgObj)=>{ 20 return ( 21 <li key={msgObj.id}> 22 23 {/* 向路由組件傳遞params參數 */} 24 {/* <Link to={`/home/message/detail/${msgObj.id}/${msgObj.title}`}>{msgObj.title}</Link> */} 25 26 {/* 向路由組件傳遞search參數 */} 27 {/* <Link to={`/home/message/detail/?id=${msgObj.id}&title=${msgObj.title}`}>{msgObj.title}</Link> */} 28 29 {/* 向路由組件傳遞state參數 */} 30 <Link to={{pathname:'/home/message/detail',state:{id:msgObj.id,title:msgObj.title}}}>{msgObj.title}</Link> 31 32 </li> 33 ) 34 }) 35 } 36 </ul> 37 <hr/> 38 {/* 聲明接收params參數 */} 39 {/* <Route path="/home/message/detail/:id/:title" component={Detail}/> */} 40 41 {/* search參數無需聲明接收,正常註冊路由即可 */} 42 {/* <Route path="/home/message/detail" component={Detail}/> */} 43 44 {/* state參數無需聲明接收,正常註冊路由即可 */} 45 <Route path="/home/message/detail" component={Detail}/> 46 47 </div> 48 ) 49 } 50 }
2. 接收參數
1 import React, { Component } from 'react' 2 // import qs from 'querystring' 3 4 const DetailData = [ 5 {id:'01',content:'你好,中國'}, 6 {id:'02',content:'你好,尚硅谷'}, 7 {id:'03',content:'你好,未來的自己'} 8 ] 9 export default class Detail extends Component { 10 render() { 11 console.log(this.props); 12 13 // 接收params參數 14 // const {id,title} = this.props.match.params 15 16 // 接收search參數 17 // const {search} = this.props.location 18 // const {id,title} = qs.parse(search.slice(1)) 19 20 // 接收state參數 21 const {id,title} = this.props.location.state || {} 22 23 const findResult = DetailData.find((detailObj)=>{ 24 return detailObj.id === id 25 }) || {} 26 return ( 27 <ul> 28 <li>ID:{id}</li> 29 <li>TITLE:{title}</li> 30 <li>CONTENT:{findResult.content}</li> 31 </ul> 32 ) 33 } 34 }