React向路由组件传参的三种方式

一、params 参数

1.路由链接

<Link to={`/home/message/detail/${msgObj.id}/${msgObj.title}`}>{msgObj.title}Link>

2.路由注册

<Route path="/home/message/detail/:id/:title" component={Detail}/>

3.参数接收

const {id,title} = this.props.match.params

二、search 参数

1.路由链接

<Link to='/demo/test?name=tom&age=18'}>详情Link>

2.路由注册

<Route path="/demo/test" component={Test}/>

3.参数接收

this.props.location.search

4.参数处理

import qs from 'querystring'

const {search} = this.props.location
const {id,title} = qs.parse(search.slice(1))

三、state参数

1.路由链接

详情Link>

2.路由注册

<Route path="/demo/test" component={Test}/>

3.参数接收

this.props.location.state

四、总结

父组件内容

import React, { Component } from 'react'
import {Link,Route} 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 (
			
    { messageArr.map((msgObj)=>{ return (
  • {/* 向路由组件传递params参数 */} {/* {msgObj.title} */} {/* 向路由组件传递search参数 */} {/* {msgObj.title} */} {/* 向路由组件传递state参数 */} {msgObj.title}
  • ) }) }

{/* 声明接收params参数 */} {/* */} {/* search参数无需声明接收,正常注册路由即可 */} {/* */} {/* state参数无需声明接收,正常注册路由即可 */}
) } }

子路由组件接收参数

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() {
		console.log(this.props);

		// 接收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 || {}

		const findResult = DetailData.find((detailObj)=>{
			return detailObj.id === id
		}) || {}
		return (
			
  • ID:{id}
  • TITLE:{title}
  • CONTENT:{findResult.content}
) } }

你可能感兴趣的:(react,js,react.js,javascript,前端)