如何在 react-router v4 中保留查询参数

IT技术 javascript reactjs react-router react-router-v4
2021-03-28 03:53:17

用户登录后重定向到我的应用程序(Java 上的服务器),他们有 url,看起来像这样 http://10.8.0.29:8083/html/?locale=RU&token=1c5c71f2-dcda-4a51-8cf6-f8f6ff1031d0&returnTo=http ://10.8.0.23:8080/

(带有一些参数,html - 是源所在的文件夹)。在我的应用程序上导航时,我需要保留这些参数。到目前为止,除了如何在保留初始查询参数的同时使用 react-router 重定向?老问题,所以我再次提出这个问题,希望如此。提前致谢。

4个回答

我已经在对您的问题的评论中分享了的 react-router v3解决方案

以下是我对 react-router v4 的解决方案。

使用以下createPreserveQueryHistory函数来覆盖history.pushhistory.replace方法,以便它们保留指定的查询参数:

import queryString from 'query-string';
import {createBrowserHistory} from 'history'

function preserveQueryParameters(history, preserve, location) {
    const currentQuery = queryString.parse(history.location.search);
    if (currentQuery) {
        const preservedQuery = {};
        for (let p of preserve) {
            const v = currentQuery[p];
            if (v) {
                preservedQuery[p] = v;
            }
        }
        if (location.search) {
            Object.assign(preservedQuery, queryString.parse(location.search));
        }
        location.search = queryString.stringify(preservedQuery);
    }
    return location;
}

function createLocationDescriptorObject(location, state) {
    return typeof location === 'string' ? { pathname: location, state } : location;
}

function createPreserveQueryHistory(createHistory, queryParameters) {
    return (options) => {
        const history = createHistory(options);
        const oldPush = history.push, oldReplace = history.replace;
        history.push = (path, state) => oldPush.apply(history, [preserveQueryParameters(history, queryParameters, createLocationDescriptorObject(path, state))]);
        history.replace = (path, state) => oldReplace.apply(history, [preserveQueryParameters(history, queryParameters, createLocationDescriptorObject(path, state))]);
        return history;
    };
}

const history = createPreserveQueryHistory(createBrowserHistory, ['locale', 'token', 'returnTo'])();

然后在路由器定义中使用它:

<Router history={history}>
    ...
</Router>

对于那些使用 TypeScript 的人

import {History, LocationDescriptor, LocationDescriptorObject} from 'history'
import queryString from 'query-string'
import LocationState = History.LocationState

type CreateHistory<O, H> = (options?: O) => History & H

function preserveQueryParameters(history: History, preserve: string[], location: LocationDescriptorObject): LocationDescriptorObject {
    const currentQuery = queryString.parse(history.location.search)
    if (currentQuery) {
        const preservedQuery: { [key: string]: unknown } = {}
        for (let p of preserve) {
            const v = currentQuery[p]
            if (v) {
                preservedQuery[p] = v
            }
        }
        if (location.search) {
            Object.assign(preservedQuery, queryString.parse(location.search))
        }
        location.search = queryString.stringify(preservedQuery)
    }
    return location
}

function createLocationDescriptorObject(location: LocationDescriptor, state?: LocationState): LocationDescriptorObject {
    return typeof location === 'string' ? {pathname: location, state} : location
}

export function createPreserveQueryHistory<O, H>(createHistory: CreateHistory<O, H>,
                                                 queryParameters: string[]): CreateHistory<O, H> {
    return (options?: O) => {
        const history = createHistory(options)
        const oldPush = history.push, oldReplace = history.replace
        history.push = (path: LocationDescriptor, state?: LocationState) =>
            oldPush.apply(history, [preserveQueryParameters(history, queryParameters, createLocationDescriptorObject(path, state))])
        history.replace = (path: LocationDescriptor, state?: LocationState) =>
            oldReplace.apply(history, [preserveQueryParameters(history, queryParameters, createLocationDescriptorObject(path, state))])
        return history
    }
}
createLocationDescriptorObject对我不起作用。我需要将{pathname: location, state}part替换{ ...parsePath(location), state }parsePath从历史中导入的位置。
2021-06-06 03:53:17
缺少搜索和哈希?
2021-06-08 03:53:17
@GennadyDogaev,上面是你的评论,什么不起作用?我用过{pathname: location, state}它似乎有效,但测试有限。我可能错过了什么?
2021-06-10 03:53:17
@innek 这是很久以前的事了,所以我不记得它不起作用的确切原因
2021-06-14 03:53:17

在 React-Router 4.3(不确定早期版本)中,如果你有一个<Route>上面的,这样的东西应该可以工作:(这是在typescript中)

Route({ path: ..., render: (props) => function() {
  Redirect({ ...,
      to: { pathname: ... search: props.location.search, ... }})
});

说明:您使用标签render: (props) => ....属性<Route>,而不是component: ...,因为render给了您props,因此<Redirect>您可以props.location.search在其中使用并以这种方式访问​​当前查询参数,并在重定向中重用。

如果没有<Route>以上,也许你不能。我只是在这里问:如何在 React-Router 4 <Switch><Redirect> 中保留查询字符串和哈希片段?

@innek 这是您认为可能发生的事情还是实际发生的事情?我认为to: ...仅适用于路径(不完全记得。)如果您Route({ ... Redirect({...动态构造列表,并排除重定向,如果您已经在mysite.com/projects?devmode=true
2021-05-30 03:53:17
这种重定向方法似乎不适用于以下场景。比如说,用户登陆了 mysite.com/home?devmode=true,并且站点导航栏上有一个菜单项,它有一个指向“mysite.com/projects”的链接。devmode=true当我点击“mysite.com/projects”时,我想改变查询参数像这样重定向会导致无限循环` <Redirect from='mysite.com/projects' to='mysite.com/projects?devmode=true' />`
2021-06-13 03:53:17

我在这个项目中关闭了哈希路由器,它保留了路由中的所有参数。

如果您需要#anchor的链接,一种选择是使用此库 https://github.com/rafrex/react-router-hash-link并执行以下操作:

import { NavHashLink } from 'react-router-hash-link';

...
<NavHashLink elementId='targetID' to='' smooth >
    
    my text
</NavHashLink>
...

这也适用于 React-Router v5。