比如这里有一条携带参数的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
})
}
很简单,但是记一下