Reactjs 带查询参数的react router generatePath

Reactjs 带查询参数的react router generatePath,reactjs,react-router,react-router-v4,react-router-dom,Reactjs,React Router,React Router V4,React Router Dom,我正在使用react路由器的内置函数generatePath生成URL。问题是,据我所知,这个函数只是返回路径,并没有提供一种机制让我们知道哪些字段添加到了路径中,哪些字段没有 例如,对于以下代码 generatePath('/user/:id', { id: 1, name: 'John', }) 函数返回的/user/1是正确的,但是我们无法知道只有id被插入到路径中,name需要作为查询参数传递 在我的应用程序中,路径模板和params对象都是动态的,我需要在params

我正在使用react路由器的内置函数
generatePath
生成URL。问题是,据我所知,这个函数只是返回路径,并没有提供一种机制让我们知道哪些字段添加到了路径中,哪些字段没有

例如,对于以下代码

generatePath('/user/:id', {
    id: 1,
    name: 'John',
})
函数返回的
/user/1
是正确的,但是我们无法知道只有
id
被插入到路径中,
name
需要作为查询参数传递
在我的应用程序中,路径模板和
params
对象都是动态的,我需要在
params
中添加额外的字段作为查询参数。

有什么方法可以做到这一点吗?

对于现在检查的任何人,我最终使用了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;
};

它匹配作为第一个参数提供的模式,在您的案例中,它恰好是
/user/:id
,因此
名称
被忽略。如果要将
名称
作为查询参数,请尝试
/user/:id?:name
不确定这是否是查询字符串的正确模式though@rikin但这意味着我需要知道名称应该提前进入查询参数。
generatePath
的第二个参数事先未知。它是基于用户输入在运行时创建的。在这种情况下,您可以使用路由器
状态
,这是一个选项,还是依赖于负责设置查询参数的其他内容。无论哪种方式,您都不需要在路由路径中声明查询参数,而只需从location对象中读取并查看其中是否有值。