react路由传递参数的几种方法

本文详细介绍了React中四种常见的路由参数传递方式:params、search、query和state,包括它们的使用方法、优缺点及参数接收方式。重点讨论了参数的传递限制和在不同场景下的适用性,对于理解React路由参数管理具有指导意义。
摘要由CSDN通过智能技术生成

params参数

  • 路由链接(携带参数):<Link to = {'/demo/test/tom/18'}> </Link >
  • 注册路由(声明接收):<Route path= '/demo/test/:name/:age' component={Test} />
  • 接收参数:this.props.match.params
  • 缺点:只能传字符串,不能传递对象,参数多导致url过长

search参数

  • 路由链接(携带参数):<Link to = {'/demo/test?name='tom'&age=18'}></Link>
  • 注册路由(无需声明接收):<Route path='/demo/test' component={Test} />
  • 接收参数:this.props.location.search
  • 备注:接收到的search是urlencoded编码字符串,需要qs解析
  • 缺点:只能传字符串,不能传递对象,参数多导致url过长

query参数

  • 路由链接(携带参数):<Link to = {{ pathname: '/demo/test' , query: {name: 'tom',age:18} }}></Link>
  • 注册路由(无需声明接收):<Route path='/demo/test' component={Test} />
  • 接收参数:this.props.location.query
  • 优点:可以传递对象
  • 缺点:HashRouter刷新地址栏,参数丢失,BrowserRouter不会丢失参数

state参数

  • 路由链接(携带参数):<Link to = {{ pathname: '/demo/test' , state: {name:'tom',age:18} }}></Link>
  • 注册路由(无需声明接收):<Route path='/demo/test' component={Test} />
  • 接收参数:this.props.location.state
  • 优点:可以传递对象
  • 缺点:HashRouter刷新地址栏,参数丢失,BrowserRouter不会丢失参数
React中,有几种方式可以实现页面跳转。其中一种方式是使用react-router-dom中的Link组件来实现页面跳转。你可以在按钮或其他组件上使用Link组件,通过to属性指定目标路径,并可以传递数据作为state属性。例如: ``` import { Link } from 'react-router-dom'; ... <Link to={{ pathname: '/path/newpath', state: { data1: {}, data2: [] } }}> <Button>点击跳转</Button> </Link> ``` 另一种方式是使用react-router-redux中的push方法进行页面跳转。你可以通过dispatch来发送push或replace方法,其中push方法可以跳转到指定路径,replace方法可以替换历史记录中的当前位置。具体使用时可以像下面这样: ``` import { push, replace } from 'react-router-redux'; ... let param1 = {}; dispatch(push("/path/newpath", param1)); dispatch(replace("/path/newpath", param1)); ``` 还有一种方式是使用RouteComponentProps中的history对象进行页面回退。你可以通过history对象的go、goForward和goBack方法来向前或向后移动历史记录中的位置。具体使用时可以像下面这样: ``` import { RouteComponentProps } from 'react-router-dom'; interface MyComponentProps extends RouteComponentProps {} ... const MyComponent: React.FC<MyComponentProps> = ({ history }) => { const handleGoBack = () => { history.goBack(); }; return ( <div> <button onClick={handleGoBack}>返回</button> </div> ); }; ``` 以上是React几种常见的路由跳转方法。你可以根据实际需求选择使用其中的一种方式来实现页面跳转。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [react路由跳转](https://blog.csdn.net/qq_46503396/article/details/123813712)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值