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

时间:2017-04-25 14:13:33

标签: javascript reactjs react-router react-router-v4

用户在登录后重定向到我的应用程序(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 - 是源位于的文件夹)。我需要在导航我的应用程序时保留这个参数。到目前为止,我没有找到任何解决这个问题的简单方法,除了这个How to redirect with react-router while preserving initial query parameters?旧问题,所以我再次提出这个问题,希望如此。提前谢谢。

4 个答案:

答案 0 :(得分:0)

很长时间没有回答问题。所以,我的回答是在这个项目中,我关闭了哈希路由器,它保留了路由中的所有参数。

答案 1 :(得分:0)

在React-Router 4.3(不确定较早的版本)中,如果上面有一个<Route>,则应该可以这样工作:(这在Typescript中)

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

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

如果上面没有props.location.search,也许您不会。我只是在这里问:How preserve query string and hash fragment, in React-Router 4 <Switch><Redirect>?

答案 2 :(得分:0)

我已经在您的问题的评论中分享了my solution的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
    }
}

答案 3 :(得分:0)

如果您需要 #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。