English 中文(简体)
反应路径生成 2. 带查询参数的路径
原标题:react-router generatePath with query parameters

I am using react-router s built in function generatePath to generate a URL. The issue is that as far as I understand this function just returns the path and doesn t provide a mechanism for us to know which fields were added in the path and which were not.

例如,以下法典:

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

the function returns /user/1 which is correct, but there is no way for us to know that only id was inserted into the path and name needs to be passed as query parameters.
In my application both the path template and the params object are dynamic and I need to add the extra fields in params as the query parameters.
Is there any way to do that ?

问题回答

对于现在检查的人,我最后使用了<代码>path-to-regexp的图书馆,这是反应堆内部用来生成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;
};




相关问题
How to use one react app into another react app?

I have two react apps, parent app and child app. and child app have an hash router. I have build the child app using npm run build, It creates build folder. That build folder moved into inside the ...

how to get selected value in Ant Design

I want to print the selected value, and below is my option list: const vesselName = [ { value: 0 , label: ALBIDDA , }, { value: 1 , label: ALRUMEILA , }, { value: 2 ,...

How to add a <br> tag in reactjs between two strings?

I am using react. I want to add a line break <br> between strings No results and Please try another search term. . I have tried No results.<br>Please try another search term. but ...

热门标签