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

查看:70
本文介绍了如何在React-Router V4中保留查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户登录后重定向到我的应用程序(Java上的服务器),并且他们具有url,看起来像这样如何在保留初始查询参数的同时使用react-router进行重定向?旧问题,所以我希望再次提出这个问题.预先感谢.

解决方案

我已经为React-Router共享了我的解决方案v3在您的问题的注释中.

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

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

 从'query-string'导入queryString;从历史"导入{createBrowserHistory}函数preserveQueryParameters(历史记录,保留内容,位置){const currentQuery = queryString.parse(history.location.search);如果(currentQuery){const reserveddQuery = {};为(保留p){const v = currentQuery [p];如果(v){reservedQuery [p] = v;}}如果(location.search){Object.assign(preservedQuery,queryString.parse(location.search));}location.search = queryString.stringify(preservedQuery);}返回位置;}函数createLocationDescriptorObject(位置,状态){返回typeof location ==='string'吗?{pathname:location,state}:位置;}函数createPreserveQueryHistory(createHistory,queryParameters){return(options)=>{const history = createHistory(options);const oldPush = history.push,oldReplace = history.replace;history.push =(路径,状态)=>oldPush.apply(history,[preserveQueryParameters(history,queryParameters,createLocationDescriptorObject(path,state))]);;history.replace =(路径,状态)=>oldReplace.apply(history,[preserveQueryParameters(history,queryParameters,createLocationDescriptorObject(path,state))]);;返回历史记录;};}const history = createPreserveQueryHistory(createBrowserHistory,['locale','token','returnTo'])(); 

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

 <路由器历史记录= {history}>...</路由器> 

对于那些使用TypeScript的人:

 从历史记录"导入{History,LocationDescriptor,LocationDescriptorObject}从'query-string'导入queryString导入LocationState = History.LocationState类型CreateHistory< O,H>=(选项?:O)=>历史与历史H函数preserveQueryParameters(历史记录:历史记录,保存区:string [],位置:LocationDescriptorObject):LocationDescriptorObject {const currentQuery = queryString.parse(history.location.search)如果(currentQuery){const reserveddQuery:{[key:string]:unknown} = {}为(保留p的保留权){const v = currentQuery [p]如果(v){reservedQuery [p] = v}}如果(location.search){Object.assign(preservedQuery,queryString.parse(location.search))}location.search = queryString.stringify(preservedQuery)}返回位置}函数createLocationDescriptorObject(location:LocationDescriptor,state ?: LocationState):LocationDescriptorObject {返回typeof location ==='string'吗?{pathname:location,state}:位置}导出函数createPreserveQueryHistory< O,H>(createHistory:CreateHistory< O,H> ;,queryParameters:string []):CreateHistory< O,H>{return(options ?: O)=>{const history = createHistory(选项)const oldPush = history.push,oldReplace = history.replacehistory.push =(路径:LocationDescriptor,状态?:LocationState)=>oldPush.apply(history,[preserveQueryParameters(history,queryParameters,createLocationDescriptorObject(path,state))])history.replace =(路径:LocationDescriptor,状态?: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天全站免登陆