ice 路由配置 redirect 支持透传 query 参数

x33g5p2x  于 2022-10-22  发布在  其他
关注(0)|答案(1)|浏览(226)

比如加个配置项:

// src/routes
export default [{
  path: '/home',
  redirect: '/about',
+  preserveQueryString: true
}]

主动开启之后 redirect 过去会携带 url query 。社区相关讨论:

hs1rzwqc

hs1rzwqc1#

目前我采用的一种临时解决办法供参考,主要思路是重定向时通过 history.replace 将所需查询参数转发到目标路由,参考代码:

// route config
const routeConfig = {
  path: '/data',
  children: [
    {
      path: '/',
      exact: true,
      component: redirect('/data/feature_db_list', ['project_id']),
    },
    {
      path: '/feature_db_list',
      component: FeatureDbList,
    },
  ]
}

/**
 * 支持透传查询参数的 redirect
 */
const redirect = (pathname, keepSearch?: boolean | string[]) => (props: IPageProps) => {
  props.history.replace({ pathname, search: getKeepSearch(keepSearch) });
  return null;
};

/**
 * 提取 search,不包含"?"
 * @param keepSearch - 为 true 时返回当前 search,为 string[] 时返回包含指定字段的 search
 */
export function getKeepSearch(keepSearch?: boolean | string[]) {
  let search = '';
  if (keepSearch) {
    const index = window.location.hash.indexOf('?');
    if (index !== -1) {
      search = window.location.hash.substring(index + 1);
    }

    if (Array.isArray(keepSearch)) {
      const usp = new URLSearchParams(search);
      search = keepSearch
        .filter((key) => usp.has(key))
        .map((key) => `${key}=${usp.get(key)}`)
        .join('&');
    }
  }
  return search;
}

相关问题