总结改变和获取 url 的方法 (包括 umi,react-router,原生)

原生: 

背景 : location.search,但返回的是一个?xxx=aa&yyy=bb 这种形式,并不能供我们正常调用,通常我们可能会用正则进行进一步截取,

快速获取当前页面的参数 : 
方法一:
location.href = 'http://www.baidu.com?ddd=1&fff=2'

const querySearch = location.search // ?ddd=1&fff=2

const queryParams = new URLSearchParams(querySearch)    // 得到URLSearchParams解析对象

const result = Object.fromEntries(queryParams.entries())    // { ddd: 1, fff: 2 }
方法二:
const params = new Proxy(new URLSearchParams(window.location.search), {
  get: (searchParams, prop) => searchParams.get(prop),
});

console.log(params) // 得到一个Proxy对象

console.log(params.ddd) // 1

封装成一个hook

const useParams = (urlSearch?) => {
    const params = useRef(
        new Proxy(new URLSearchParams(urlSearch || window.location.search), {
            get: (searchParams, prop) => searchParams.get(prop),
        })
    );

    return params.current
}

Umi:

useParams

useParams 钩子函数返回动态路由的匹配参数键值对对象;子路由中会集成父路由的动态参数。

import { useParams } from 'umi';

// 假设有路由配置  user/:uId/repo/:rId
// 当前路径       user/abc/repo/def
const params = useParams()
/* params
{ uId: 'abc', rId: 'def'}
*/

跳转/获取路由 : 

import { history,history  } from 'umi';

// 正确的在组件或页面中执行路由导航
const handleClick = () => {
  history.push('/app-settings/popular', { data: '这是一些状态数据' });
};



// 通过  history.location.query 获取
if (history.location.query?.id || history.location.query?.draftId) 

获取路由参数:

  const state: any = useLocation().state // 获取上面方法的数据

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值