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

How to preserve query parameters in 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? 老问题,我还没有找到解决这个问题的任何简单方法,所以我再次提出这个问题,希望如此。提前致谢。

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

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

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

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

如果上面没有<Route>,也许你做不到。我只是在这里问:How preserve query string and hash fragment, in React-Router 4 <Switch><Redirect>?

我已经在对你的问题的评论中为 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
    }
}

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

它与 react-router 的 useLocation hook 一起正常工作,试试下面的方法

import { Link, useLocation } from 'react-router-dom';
    
function CustomPage() {

      const { search } = useLocation();
    
      return (
        <>
          <p>Preserve the query params?</p>
          <Link to={`/your-next-location${search}`}>Next link</Link>
        </>
      );
 }

或者通过push方式进行路由导航

 import { useHistory, useLocation } from 'react-router-dom';
 /*...
   .
   .
 ...*/
 const history = useHistory();
 const { search } = useLocation();
 /*...
   .
   .
 ...*/
 history.push({pathname:`/your-next-location${search}`});