欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

React獲取url后面參數(shù)的值示例代碼

 更新時(shí)間:2022年12月07日 11:29:08   作者:SeveCc  
這篇文章主要介紹了React獲取url后面參數(shù)的值示例代碼,代碼簡(jiǎn)單易懂,文末給大家補(bǔ)充介紹了react獲取URL中參數(shù)方法,需要的朋友可以參考下

React獲取url后面參數(shù)的值

由于頁(yè)面跳轉(zhuǎn)需要取攜帶的token訪問(wèn)數(shù)據(jù)。

寫一個(gè)公共方法

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;
		}

在要獲取值得頁(yè)面進(jìn)行引入

import { getUrlToken } from '寫你建立公共方法的地址';

		//  結(jié)果測(cè)試
		constructor(peops){
			super(peops);
			const token = getUrlToken ('token',peops.location.search);
			console.log(token );
		}

測(cè)試結(jié)果

擴(kuò)展知識(shí):

react獲取URL中參數(shù)

這個(gè)問(wèn)題想必很多人都會(huì)遇到過(guò),這里我說(shuō)一下怎么獲取URL中的參數(shù)。

react 獲取URL原理:

在 react 組件的 componentDidMount 方法中打印一下 this.props,在瀏覽器控制臺(tái)中查看輸出如下:

其中頁(yè)面的 url 信息全都包含在 match 字段中,

以地址  localhost:3000/app/knowledgeManagement/modify/STY20171011124209535/3/1507701970070/0/?s=1&f=7  為例

其中各個(gè)參數(shù)定義對(duì)應(yīng)如下:

localhost:3000/app/knowledgeManagement/modify/:studyNo/:stepId/:randomNum/:isDefault/?s=&f=

首先打印 this.props.match

可以看到 this.props.match 中包含的 url 信息還是非常豐富的,其中

history: 包含了組件可以使用的各種路由系統(tǒng)的方法,常用的有 push 和 replace,兩者都是跳轉(zhuǎn)頁(yè)面,但是 replace 不會(huì)引起頁(yè)面的刷新,僅僅是改變 url。

location: 相當(dāng)于URL 的對(duì)象形式表示,通過(guò) search 字段可以獲取到 url 中的 query 信息。(這里 state 的含義與 HTML5 history.pushState API 中的 state 對(duì)象一樣。每個(gè) URL 都會(huì)對(duì)應(yīng)一個(gè) state 對(duì)象,你可以在對(duì)象里存儲(chǔ)數(shù)據(jù),但這個(gè)數(shù)據(jù)卻不會(huì)出現(xiàn)在 URL 中。實(shí)際上,數(shù)據(jù)被存在了 sessionStorage 中)(參考: 深入理解 react-router 路由系統(tǒng))

match: 包含了具體的 url 信息,在 params 字段中可以獲取到各個(gè)路由參數(shù)的值。

通過(guò)以上分析,獲取 url 中的指定參數(shù)就十分簡(jiǎn)單了,下面是幾個(gè)例子:

// 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'

注意點(diǎn):

如果這個(gè)值需要在頁(yè)面中及時(shí)獲得,這個(gè)時(shí)候就需要注意了,我們都知道react是有生命周期的,那么什么時(shí)候獲取URL的值最合適呢?

  • 這個(gè)我推薦在componentDidMount 這個(gè)生命周期的時(shí)候去獲取,因?yàn)檫@個(gè)時(shí)候頁(yè)面已經(jīng)掛在好了,完全可以拿到URL上面的值。

到此這篇關(guān)于React獲取url后面參數(shù)的值示例代碼的文章就介紹到這了,更多相關(guān)React獲取url參數(shù)的值內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論