导航客户端时在 NextJS 中保留查询字符串参数
Persist query string parameters in NextJS when navigating client side
将 nextjs
与 next-routes
结合使用,是否可以在页面之间导航时保留 URL 的查询字符串?我有一个广告活动 运行,出于历史原因和跟踪,我需要在浏览页面时保留它。
我不能将其填充到 Redux 存储、本地主机、会话存储等中。它必须保留在 URL。
我尝试了如下操作:
import { Router } from 'routes';
Router.events.on('routeChangeStart', (url: string) => {
if (Router.query && Router.router.pathname !== url) {
const href = `${url}${Object.keys(Router.query).reduce(
(carry: string, key: string) => {
carry += `${carry === '' ? '?' : '&'}${key}=${Router.query[key]}`;
return carry;
},'')}`;
Router.pushRoute(href, Router.router.pathname, { shallow: true });
}
});
并且 routes.js
文件导出 next-routes
:
const nextRoutes = require('next-routes');
const routes = (module.exports = nextRoutes());
这里发生的是 URL 被正确推送并且查询字符串持续存在,但只是短暂的闪烁。它立即将原始 url
推回路由器,我丢失了我的查询字符串参数。
我尝试了其他几种变体,但不幸的是我找不到正确的实现方式。
感谢任何帮助。
经过一番搜索,我设法得到了我想要的结果:
const customRouter = (module.exports = nextRoutes());
customRouter.Router.pushRouteWithQuery = function(route, params, options) {
if(!params || !Object.keys(params).length) {
const routeWithParams = QueryStringHelper.generateUrlWithQueryString(route, customRouter.Router.router.query);
customRouter.Router.pushRoute(routeWithParams, params, options);
} else {
const filteredParams = QueryStringHelper.filterAllowedParams(customRouter.Router.router.query);
const allParams = {
...filteredParams,
...params
};
customRouter.Router.pushRoute(route, allParams, options);
}
}
然后我将使用我新创建的方法重定向到具有所需查询字符串的另一个页面:
import { Router } from 'my/module'
Router.pushRouteWithQuery('/home');
最后 QueryStringHelper
:
module.exports = {
generateUrlWithQueryString,
getAllowedParams,
prepareParamsAsQueryString,
filterAllowedParams
}
function getAllowedParams() {
const allowedParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'mid', 'gclid', 'source'];
return allowedParams;
}
function prepareParamsAsQueryString() {
const params = getAllowedParams();
let paramsLikeQueryString = [];
for (let index = 0; index < params.length; index++) {
const param = params[index];
paramsLikeQueryString.push(`${param}=:${param}?`);
}
return paramsLikeQueryString.join('&');
}
function generateUrlWithQueryString(url, params) {
if(Object.keys(params).length) {
const filteredParams = filterAllowedParams(params);
if (Object.keys(filteredParams).length) {
if(url[0] != '/')
url = `/${url}`;
return `${url}?${serialize(filteredParams)}`;
}
return url;
}
return url;
}
function filterAllowedParams(params) {
if(Object.keys(params).length) {
const filteredParams = Object.keys(params)
.filter(key => getAllowedParams().includes(key.toLowerCase()))
.reduce((obj, key) => {
obj[key] = params[key];
return obj;
}, {});
return filteredParams;
}
return params;
}
// INTERNAL
function serialize(obj) {
var str = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
}
return str.join("&");
}
我从 URL 获取了查询字符串,并在我使用该组件的任何地方都将其传递了很长时间。
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
export const getUrlPathParams = (): string => {
const [pathParams, setPathParams] = useState("");
useEffect(() => {
setPathParams(router?.asPath?.slice(router?.pathname?.length));
});
const router = useRouter();
return pathParams;
};
以及在 link 中使用它的示例。
<Link href={"/" + getUrlPathParams()}> Home </Link>
我正在为我的外部 link 做同样的事情,以便我的广告活动有效。
对我们有帮助的是 URL and URLSearchParams API。
我们创建了一些在使用 router.push
时使用的小方法,这里是一个更改路由但保留查询参数的示例:
/**
*
* @param currentPath the current asPath the user is on, eg /stuff/example/more-stuff?utm-campaing=test
* @param newPath the new path we want to push to the router, eg /stuff/example/even-more-stuff
* @returns the newPath with the query params from the existing path, eg /stuff/example/even-more-stuff?utm-campaing=test
*/
export const changeRouteKeepParams = (
currentPath: string,
newPath: string
): string => {
const hasQueries = currentPath.indexOf('?');
const searchQuery = hasQueries >= 0 ? currentPath.substring(hasQueries) : '';
const params = new URLSearchParams(searchQuery);
const paramsStr = params.toString() !== '' ? `?${params.toString()}` : '';
return `${newPath}${paramsStr}`;
};
npm install query-string
import Link from 'next/link'
import {useRouter} from 'next/router'
import queryString from 'query-string'
export const Example = () => {
const router = useRouter()
const query = queryString.stringify(router.query)
const url = query ? `${router.pathname}?${query}` : router.pathname
return <Link href={url}></Link>
}
将 nextjs
与 next-routes
结合使用,是否可以在页面之间导航时保留 URL 的查询字符串?我有一个广告活动 运行,出于历史原因和跟踪,我需要在浏览页面时保留它。
我不能将其填充到 Redux 存储、本地主机、会话存储等中。它必须保留在 URL。
我尝试了如下操作:
import { Router } from 'routes';
Router.events.on('routeChangeStart', (url: string) => {
if (Router.query && Router.router.pathname !== url) {
const href = `${url}${Object.keys(Router.query).reduce(
(carry: string, key: string) => {
carry += `${carry === '' ? '?' : '&'}${key}=${Router.query[key]}`;
return carry;
},'')}`;
Router.pushRoute(href, Router.router.pathname, { shallow: true });
}
});
并且 routes.js
文件导出 next-routes
:
const nextRoutes = require('next-routes');
const routes = (module.exports = nextRoutes());
这里发生的是 URL 被正确推送并且查询字符串持续存在,但只是短暂的闪烁。它立即将原始 url
推回路由器,我丢失了我的查询字符串参数。
我尝试了其他几种变体,但不幸的是我找不到正确的实现方式。
感谢任何帮助。
经过一番搜索,我设法得到了我想要的结果:
const customRouter = (module.exports = nextRoutes());
customRouter.Router.pushRouteWithQuery = function(route, params, options) {
if(!params || !Object.keys(params).length) {
const routeWithParams = QueryStringHelper.generateUrlWithQueryString(route, customRouter.Router.router.query);
customRouter.Router.pushRoute(routeWithParams, params, options);
} else {
const filteredParams = QueryStringHelper.filterAllowedParams(customRouter.Router.router.query);
const allParams = {
...filteredParams,
...params
};
customRouter.Router.pushRoute(route, allParams, options);
}
}
然后我将使用我新创建的方法重定向到具有所需查询字符串的另一个页面:
import { Router } from 'my/module'
Router.pushRouteWithQuery('/home');
最后 QueryStringHelper
:
module.exports = {
generateUrlWithQueryString,
getAllowedParams,
prepareParamsAsQueryString,
filterAllowedParams
}
function getAllowedParams() {
const allowedParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'mid', 'gclid', 'source'];
return allowedParams;
}
function prepareParamsAsQueryString() {
const params = getAllowedParams();
let paramsLikeQueryString = [];
for (let index = 0; index < params.length; index++) {
const param = params[index];
paramsLikeQueryString.push(`${param}=:${param}?`);
}
return paramsLikeQueryString.join('&');
}
function generateUrlWithQueryString(url, params) {
if(Object.keys(params).length) {
const filteredParams = filterAllowedParams(params);
if (Object.keys(filteredParams).length) {
if(url[0] != '/')
url = `/${url}`;
return `${url}?${serialize(filteredParams)}`;
}
return url;
}
return url;
}
function filterAllowedParams(params) {
if(Object.keys(params).length) {
const filteredParams = Object.keys(params)
.filter(key => getAllowedParams().includes(key.toLowerCase()))
.reduce((obj, key) => {
obj[key] = params[key];
return obj;
}, {});
return filteredParams;
}
return params;
}
// INTERNAL
function serialize(obj) {
var str = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
}
return str.join("&");
}
我从 URL 获取了查询字符串,并在我使用该组件的任何地方都将其传递了很长时间。
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
export const getUrlPathParams = (): string => {
const [pathParams, setPathParams] = useState("");
useEffect(() => {
setPathParams(router?.asPath?.slice(router?.pathname?.length));
});
const router = useRouter();
return pathParams;
};
以及在 link 中使用它的示例。
<Link href={"/" + getUrlPathParams()}> Home </Link>
我正在为我的外部 link 做同样的事情,以便我的广告活动有效。
对我们有帮助的是 URL and URLSearchParams API。
我们创建了一些在使用 router.push
时使用的小方法,这里是一个更改路由但保留查询参数的示例:
/**
*
* @param currentPath the current asPath the user is on, eg /stuff/example/more-stuff?utm-campaing=test
* @param newPath the new path we want to push to the router, eg /stuff/example/even-more-stuff
* @returns the newPath with the query params from the existing path, eg /stuff/example/even-more-stuff?utm-campaing=test
*/
export const changeRouteKeepParams = (
currentPath: string,
newPath: string
): string => {
const hasQueries = currentPath.indexOf('?');
const searchQuery = hasQueries >= 0 ? currentPath.substring(hasQueries) : '';
const params = new URLSearchParams(searchQuery);
const paramsStr = params.toString() !== '' ? `?${params.toString()}` : '';
return `${newPath}${paramsStr}`;
};
npm install query-string
import Link from 'next/link'
import {useRouter} from 'next/router'
import queryString from 'query-string'
export const Example = () => {
const router = useRouter()
const query = queryString.stringify(router.query)
const url = query ? `${router.pathname}?${query}` : router.pathname
return <Link href={url}></Link>
}