React路由参数
工作中开发react项目时遇到了路由参数的问题。当时因为基础不好,解决这个问题花了很长时间,出现了bug。特此记录。项目中的路由跳转使用的是hashRouter。由于详情页跳转到审批页,所以携带了很多参数。一开始使用state传递参数,导致页面刷新参数丢失。最后,使用动态路由传递参数。代码如下::hrNo"component={Opinion}/>
//页面跳转this.props.history.push(`/opinion/id/reSwapId/reSwapType/recordId/auditId/approver/teamId/busiIds/mobile/postName/hrNo`)//参数接收const{opinion,id,reSwapId,reSwapType,recordId,auditId,approver,teamId,busiIds,mobile,postName,hrNo}=this.props.match.params;看似解决了问题,但是因为其中一个参数为空,直接导致审批页面报错,最后还是把参数传给了一个对象。代码如下:
//页面跳转constopinionParams={"reSwapId":reSwapId,“reSwapType”:reSwapType,“recordId”:recordId,“auditId”:auditId,“approver”:approver,“teamId”:teamId,“busiIds”:busiIds,“mobile”:mobile,“postName”:postName,“hrNo”":hrNo}constjsonData=JSON.Stringfy(opinionParams);this.props.history.push(`/opinion/${id}/${jsonData}`)//接收参数constjsonData=this.props.match.params.json数据;const{opinion,id,reSwapId,reSwapType,recordId,auditId,approver,teamId,busiIds,mobile,postName,hrNo}=jsonData;这个问题成功解决,即使参数是也不会报错空的。这个问题看似很简单,但是当时却花了我很长的时间。看来基础知识储备不足确实影响开发效率,尤其是出现bug的时候,自己会毫无头绪,导致时间的浪费。借此机会研究总结一下react路由参数。不要害怕以后遇到这样的问题。React路由传参方法paramsRoutepath="/list/:id"component={List}
跳转页面//页面跳转:this.props.history.push("/list/2");//列表页面接收:console.log(this.props.match.params.id)//传入的所有参数优点:页面刷新,参数不会丢失;缺点:传太多值不方便,url会变得很长。2.statethis.props.history.push({pathname:"/sort",state:{name:'sunny'}});//读取参数:this.props.location.query.state;优点:传参优雅,传参可以传对象;缺点:如果使用HashRouter,如果刷新页面,参数会丢失;3.搜索xxxthis.props.history.push({pathname:"/web/departManange?tenantId"+row.tenantId});使用读取参数:this.props.location.search优点:页面刷新,参数不会丢失;缺点:如果传的值太多,url也会变得很长。4.querythis.props.history.push({pathname:"/query",query:{name:'sunny'}});使用读取参数:this.props.location.query.name优点:参数传递优雅,可以通过参数传递对象;缺点:刷新地址栏,缺少参数。