背景 : 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
- }
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 // 获取上面方法的数据