react如何獲取頁面跳轉url攜帶的參數

比如這裏有一條攜帶參數的url。http://baidu.com?type=1
我們要取出type的值。
因爲獲取頁面跳轉url攜帶的參數比較常用,所以我們把它封裝成一個工具函數。
在src根目錄下新建一個文件util.js
封裝一個獲取url參數的函數。

export function getUrlParams(name, str) {
    const reg = new RegExp(`(^|&)${ name}=([^&]*)(&|$)`);
    const r = str.substr(1).match(reg);
    if (r != null) return  decodeURIComponent(r[2]); return null;
}

使用的時候,在當前頁面導入這個函數

import { getUrlParams } from '../../util'

接下來就可以在componentDidMount之中獲取這個type值

 componentDidMount(){
    const type = getUrlParams ('type',this.props.location.search);
    this.setState({
      type	//設置state
    })    
  }
     

很簡單,但是記一下

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章