React Router v5如何复用PATH常量带路由参数调用history.push
react-router-dom@5.x 及配套的history库本身没有提供在history.push里自动填充路由参数的内置能力,但你可以用官方自带的工具方法或者简单封装实现需求。
方案1:直接使用官方自带的generatePath方法
react-router-dom v5 已经内置了generatePath工具函数,专门用来填充带占位符的路由模板,用法如下:
import { generatePath } from 'react-router-dom'; // 直接生成路径后跳转 history.push(generatePath(PATH.editProduct, { productId: "2" }));
该方法会自动把路由模板里的占位符替换为传入的参数值,最终生成/edit-product/2的目标路径。
方案2:封装自定义跳转方法,实现你要的调用格式
如果你想要保持history.push({pathname: xxx, routerParam: xxx})的调用形式,可以对原生history的push方法做一层封装:
- 先封装自定义的useHistory钩子:
import { useHistory as useRawHistory, generatePath } from 'react-router-dom'; export const useHistory = () => { const history = useRawHistory(); const rawPush = history.push; history.push = (location) => { // 处理带routerParam的跳转场景 if (typeof location === 'object' && location.routerParam && location.pathname) { const parsedPath = generatePath(location.pathname, location.routerParam); return rawPush({ ...location, pathname: parsedPath }); } // 其他场景走原生逻辑 return rawPush(location); }; return history; };
- 组件内使用封装后的钩子即可按你期望的方式调用:
const history = useHistory(); // 直接按你想要的格式传参 history.push({ pathname: PATH.editProduct, routerParam: {productId: "2"} });
自定义实现generatePath(可选)
如果你不想依赖官方的generatePath,也可以自己实现一个简单的参数替换函数:
function generatePath(pathTemplate, params) { return pathTemplate.replace(/:(\w+)/g, (match, paramKey) => { return params[paramKey] ?? match; }); }
这个函数可以实现和官方方法一致的基础参数填充能力。
内容的提问来源于stack exchange,提问作者Polpo
相关产品推荐
相关产品推荐

