带有查询参数的react-routergeneratePath

问题描述 投票:0回答:1

我正在使用react-router的内置函数

generatePath
来生成URL。问题是,据我了解,这个函数只是返回路径,并没有提供一种机制让我们知道哪些字段已添加到路径中,哪些字段没有添加。

例如下面的代码

generatePath('/user/:id', {
    id: 1,
    name: 'John',
})

函数返回

/user/1
,这是正确的,但我们无法知道只有
id
被插入到路径中,并且
name
需要作为查询参数传递。
在我的应用程序中,路径模板和
params
对象都是动态的,我需要在
params
中添加额外字段作为查询参数。
有什么办法可以做到吗?

reactjs react-router react-router-v4 react-router-dom
1个回答
0
投票

对于现在检查的人来说,我最终使用了

path-to-regexp
库,它是 React-router 内部使用的用于生成 URL 的库。代码看起来像这样

import pathToRegexp from 'path-to-regexp';
import qs from 'qs';

const compiledCache = {};
export default function generatePathWithQueryParams(rawPath, params) {
    let toPath;
    if (compiledCache[rawPath]) {
        toPath = compiledCache[rawPath];
    } else {
        toPath = pathToRegexp.compile(rawPath);
        compiledCache[rawPath] = toPath;
    }
    const queryParams = { ...params };
    const path = toPath(params, {
        encode: (value, token) => {
            delete queryParams[token.name];
            return encodeURI(value);
        },
    });
    const queryString = qs.stringify(queryParams);
    if (queryString) {
        return `${path}?${queryString}`;
    }
    return path;
};
© www.soinside.com 2019 - 2024. All rights reserved.