React获取url后面参数的值 由于页面跳转需要取携带的token访问数据。 写一个公共方法 export function getUrlToken(name, str) {
由于页面跳转需要取携带的token访问数据。
写一个公共方法
export function getUrlToken(name, str) {
const reg = new RegExp(`(^|&)${ name}=([^&]*)(&|$)`);
const r = str.substr(1).match(reg);
if (r != null) return decodeURIComponent(r[2]); return null;
}
在要获取值得页面进行引入
import { getUrlToken } from '写你建立公共方法的地址';
// 结果测试
constructor(peops){
super(peops);
const token = getUrlToken ('token',peops.location.search);
console.log(token );
}
测试结果
扩展知识:
这个问题想必很多人都会遇到过,这里我说一下怎么获取URL中的参数。
在 react 组件的 componentDidMount 方法中打印一下 this.props,在浏览器控制台中查看输出如下:
其中页面的 url 信息全都包含在 match 字段中,
以地址 localhost:3000/app/knowledgeManagement/modify/STY20171011124209535/3/1507701970070/0/?s=1&f=7 为例
其中各个参数定义对应如下:
localhost:3000/app/knowledgeManagement/modify/:studyNo/:stepId/:randomNum/:isDefault/?s=&f=
首先打印 this.props.match :
可以看到 this.props.match 中包含的 url 信息还是非常丰富的,其中
history: 包含了组件可以使用的各种路由系统的方法,常用的有 push 和 replace,两者都是跳转页面,但是 replace 不会引起页面的刷新,仅仅是改变 url。
location: 相当于URL 的对象形式表示,通过 search 字段可以获取到 url 中的 query 信息。(这里 state 的含义与 HTML5 history.pushState api 中的 state 对象一样。每个 URL 都会对应一个 state 对象,你可以在对象里存储数据,但这个数据却不会出现在 URL 中。实际上,数据被存在了 sessionStorage 中)(参考: 深入理解 react-router 路由系统)
match: 包含了具体的 url 信息,在 params 字段中可以获取到各个路由参数的值。
通过以上分析,获取 url 中的指定参数就十分简单了,下面是几个例子:
// localhost:3000/app/knowledgeManagement/modify/STY20171011124209535/3/1507701970070/0/?s=1&f=7
// localhost:3000/app/knowledgeManagement/modify/:studyNo/:stepId/:randomNum/:isDefault/?s=1&f=7
// 获取 studyNo
this.props.match.match.params.studyNo // STY20171011124209535
// 获取 stepId
this.props.match.match.params.stepId // 3
// 获取 success
const query = this.props.match.location.search // '?s=1&f=7'
const arr = query.split('&') // ['?s=', 'f=7']
const successCount = arr[0].substr(3) // '1'
const failedCount = arr[1].substr(2) // '7'
如果这个值需要在页面中及时获得,这个时候就需要注意了,我们都知道react是有生命周期的,那么什么时候获取URL的值最合适呢?
到此这篇关于React获取url后面参数的值示例代码的文章就介绍到这了,更多相关React获取url参数的值内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: React获取url后面参数的值示例代码
本文链接: https://www.lsjlt.com/news/174479.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0