如何在 react-router v4 中保留查询参数 [英] How to preserve query parameters in react-router v4

查看:20
本文介绍了如何在 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 - 是源所在的文件夹).在我的应用程序上导航时,我需要保留这些参数.到目前为止,除了这个 如何在保留初始查询参数的同时使用 react-router 重定向? 老问题,所以我再次提出这个问题,希望如此.提前致谢.

解决方案

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

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

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

import queryString from 'query-string';从历史"导入 {createBrowserHistory}函数保留查询参数(历史,保留,位置){const currentQuery = queryString.parse(history.location.search);如果(当前查询){常量保留查询 = {};对于(让 p 保留){const v = currentQuery[p];如果(五){保留查询[p] = v;}}如果(位置.搜索){Object.assign(preservedQuery, queryString.parse(location.search));}location.search = queryString.stringify(preservedQuery);}返回地点;}函数 createLocationDescriptorObject(位置,状态){返回类型位置 === 'string' ?{路径名:位置,状态}:位置;}函数 createPreserveQueryHistory(createHistory, queryParameters) {返回(选项)=>{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))]);返回历史;};}const history = createPreserveQueryHistory(createBrowserHistory, ['locale', 'token', 'returnTo'])();

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

...</路由器>

对于使用 TypeScript 的人:

从'history'导入{History, LocationDescriptor, LocationDescriptorObject}从查询字符串"导入查询字符串导入 LocationState = History.LocationState输入 CreateHistory=(选项?:O)=>历史与H函数preserveQueryParameters(history: History, preserve: string[], location: LocationDescriptorObject): LocationDescriptorObject {const currentQuery = queryString.parse(history.location.search)如果(当前查询){const reservedQuery: { [key: string]: unknown } = {}对于(让 p 保留){const v = currentQuery[p]如果(五){保留查询[p] = v}}如果(位置.搜索){Object.assign(preservedQuery, queryString.parse(location.search))}location.search = queryString.stringify(preservedQuery)}返回地点}function createLocationDescriptorObject(location: LocationDescriptor, state?: LocationState): LocationDescriptorObject {返回类型位置 === 'string' ?{路径名:位置,状态}:位置}导出函数 createPreserveQueryHistory(createHistory: CreateHistory,queryParameters: string[]): CreateHistory{返回(选项?:O)=>{const history = createHistory(选项)const oldPush = history.push, oldReplace = history.replacehistory.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))])返回历史}}

Users redirected to my app after login (server on java), and they have url, which looks like this http://10.8.0.29:8083/html/?locale=RU&token=1c5c71f2-dcda-4a51-8cf6-f8f6ff1031d0&returnTo=http://10.8.0.23:8080/

(with some params, html - is folder where sources located). I need to preserve this params while navigate on my app. So far I didn't found any simple solution to this problem except this How to redirect with react-router while preserving initial query parameters? old question, so I arise this question again, in hope. Thanks in advance.

解决方案

I already shared my solution for react-router v3 in the comment to your question.

Below is my solution for react-router v4.

Use the following createPreserveQueryHistory function to override history.push and history.replace methods so they will preserve specified query parameters:

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'])();

Then use it in your router definition:

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

For those who use 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
    }
}

这篇关于如何在 react-router v4 中保留查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆