我正在使用 react 17.0.2 并定义了这样的路由:
export const PATH = {
editProduct: '/edit-product/:productId'
}
export const routes = [
{
path: PATH.editProduct,
render: (props) => <Product {...props}/>
}
]
export const useRoutes = () => ({ PATH, routes });
然后路由与“react-router-dom”版本一起使用:^5.2.0
以前一些没有路由参数的路径使用 history.push(PATH.somePath);
并且它有效,但我想在某些组件中使用 react routerParams。
喜欢:
history.push({pathname: PATH.editProduct, routerParam: {productId: "2"} });
以前带有路由参数的路径是通过不使用 PATH 变量传递的,而是键入像 history.push('/edit-product/' + productId);
这样的字符串我想重用PATH 变量,但我不知道如何巧妙地实现它。
如果我在 history.push 方法中使用 PATH.editProduct,它会像/edit-product/:productId 一样放置路由参数,这不是我想要的行为。历史上有routeparams的解析方法吗?
最佳答案
react-router-dom
中有generatePath
util。
import { generatePath } from "react-router-dom";
const path = generatePath(PATH.editProduct, {
productId: 1
});
history.push(path);
关于reactjs - 历史上的 React Router RouteParams,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68903663/