英文:
How to change and add query strings in the app folder of Next.js?
问题
在pages
文件夹中,使用以下方式更新URL的router
,我如何在app
目录中更改查询参数?我使用Next.js版本13.4
。
英文:
With the router
in pages
folder, I update the url like below:
router.push({
query: {
...router.query,
page: newPage + 1
}
})
How I can change the query parameters in the app
directory? I use Next.js 13.4
.
答案1
得分: 1
在app
文件夹中,router.push(href: string)
作为参数仅接受字符串形式的 href
。你需要自己设置查询参数,就像在这个 示例 中所展示的那样。
设置方法如下:
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
export default function ExampleClientComponent() {
const router = useRouter();
const createQueryString = (name, value) => {
const params = new URLSearchParams();
params.set(name, value);
return params.toString();
};
return (
<>
{/* 使用 useRouter */}
<button
onClick={() => {
router.push("/posts" + "?" + createQueryString("sort", "asc"));
}}
>
ASC
</button>
{/* 使用<Link> */}
<Link href={"/posts" + "?" + createQueryString("sort", "desc")}>DESC</Link>
</>
);
}
你可以通过传递给页面组件的 searchParams
来读取它:
// app/posts/page.js
export default function Page({ searchParams }) {
return <div>{searchParams.sort}</div>;
}
或者在任何客户端组件中使用 useSearchParams
函数:
"use client";
import { useSearchParams } from "next/navigation";
export default function Page() {
const searchParams = useSearchParams();
return <div>{searchParams.get("sort")}</div>;
}
英文:
In the app
folder, router.push(href: string)
accepts as a parameter only the href
as a string. You need to set query parameters yourself, as they show in this example.
You set it this way:
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
export default function ExampleClientComponent() {
const router = useRouter();
const createQueryString = (name, value) => {
const params = new URLSearchParams();
params.set(name, value);
return params.toString();
};
return (
<>
{/* using useRouter */}
<button
onClick={() => {
router.push("/posts" + "?" + createQueryString("sort", "asc"));
}}
>
ASC
</button>
{/* using <Link> */}
<Link href={"/posts" + "?" + createQueryString("sort", "desc")}>DESC</Link>
</>
);
}
You would read it with the searchParams
passed to your page component:
// app/posts/page.js
export default function Page({ searchParams }) {
return <div>{searchParams.sort}</div>;
}
Or using the useSearchParams
function in any client component:
"use client";
import { useSearchParams } from "next/navigation";
export default function Page() {
const searchParams = useSearchParams();
return <div>{searchParams.get("sort")}</div>;
}
答案2
得分: 0
I wrote a function for using query strings:
export const createQueryString = (pathname, router, name: string, value: string) => {
let searchParams = new URLSearchParams(window.location.search)
if (value) {
if (!Array.isArray(value)) {
if (!searchParams.has(name)) searchParams.append(name, value)
else searchParams.set(name, value)
} else {
if (!searchParams.has(name)) searchParams.append(name, value.join())
else searchParams.set(name, value.join())
}
} else if (searchParams.has(name)) searchParams.delete(name)
const newUrl = pathname + '?' + searchParams.toString()
router.push(newUrl)
}
and in my component, I called it.
pass pathname
and router
from 'next/navigation'
to createQueryString
function:
import { createQueryString } from 'helpers'
import { usePathname, useRouter } from 'next/navigation'
const TablePagination = ({ pagination }: Props) => {
const router = useRouter()
const pathname = usePathname()
return (
<Pagination
count={50}
rowsPerPage={10}
page={pagination.page - 1}
onPageChange={(event, page) => createQueryString(pathname, router, 'page', `${page + 1}`)}
onRowsPerPageChange={(event) =>
createQueryString(pathname, router, 'take', event.target.value)
}
/>
)
}
英文:
I wrote a function for using query strings
export const createQueryString = (pathname, router, name: string, value: string) => {
let searchParams = new URLSearchParams(window.location.search)
if (value) {
if (!Array.isArray(value)) {
if (!searchParams.has(name)) searchParams.append(name, value)
else searchParams.set(name, value)
} else {
if (!searchParams.has(name)) searchParams.append(name, value.join())
else searchParams.set(name, value.join())
}
} else if (searchParams.has(name)) searchParams.delete(name)
const newUrl = pathname + '?' + searchParams.toString()
router.push(newUrl)
}
and in my component, I called it.
pass pathname
and router
from 'next/navigation'
to createQueryString
function
import { createQueryString } from 'helpers'
import { usePathname, useRouter } from 'next/navigation'
const TablePagination = ({ pagination }: Props) => {
const router = useRouter()
const pathname = usePathname()
return (
<Pagination
count={50}
rowsPerPage={10}
page={pagination.page - 1}
onPageChange={(event, page) => createQueryString(pathname, router, 'page', `${page + 1}`)}
onRowsPerPageChange={(event) =>
createQueryString(pathname, router, 'take', event.target.value)
}
/>
)
}
答案3
得分: 0
这个辅助函数可以处理多个查询:
const createQueryString = useCallback(
(query) => {
const params = new URLSearchParams(searchParams);
for (const [name, value] of Object.entries(query)) {
if (name !== null && value !== undefined) {
params.set(name, value);
}
}
return params.toString();
}, [searchParams]
);
并且在客户端组件中像这样使用它:
const query = {
category: 'cars',
section: 'vehicles',
};
router.push(`/?${createQueryString(query)}`);
只需确保从 'next-navigation' 或 'next-intl/client' 中导入 router。
英文:
this helper function handle multipe queries at once:
const createQueryString = useCallback(
(query)=> {
const params = new URLSearchParams(searchParams);
for(const [name, value] of Object.entries(query)){
if(name !== null && value !== undefined) {
params.set(name, value);
}
}
return params.toString();
}, [searchParams]
);
and use it in client component like this:
const query = {
category: 'cars',
section: 'vehicles',
};
router.push(`/?${createQueryString(query)}`);
just make sure that router is imported from 'next-navigation' or 'next-intl/client'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论