您可以使用搜索参数来做到这一点。 我会给你一个例子来说明如何做。
首先创建一个名为 useSearchParams 的新钩子
import { useSearchParams, useRouter, usePathname } from 'next/navigation'
import { useCallback } from 'react'
const useSearchState = () => {
const router = useRouter()
const searchParams = useSearchParams()
const pathname = usePathname()
const createQueryString = useCallback(
(name: string, value: string) => {
const params = new URLSearchParams(searchParams.toString())
params.set(name, value)
return params.toString()
},
[searchParams]
)
const push = (key: string, value: string) => {
router.replace((pathname + '?' + createQueryString(key, value)))
}
return { push, createQueryString, get: searchParams.get, searchParams }
}
export default useSearchState
那么您的排序下拉组件应该是客户端组件,就像我在项目中所做的那样
'use client'
export function IntegratedRecordsYearFilter() {
const { push } = useSearchState()
return (
<Select onValueChange={(value) => push('yourSearchParamKey', value)}>
<SelectTrigger className="min-w-36 md:min-w-64">
<SelectValue placeholder="Filter records" />
</SelectTrigger>
<SelectContent>
{years.map((year: number) => (
<SelectItem key={year} value={String(year)}>
<div className="flex items-center gap-2">{year}</div>
</SelectItem>
))}
</SelectContent>
</Select>
)
}
现在您可以从服务器组件访问搜索参数键,并在搜索参数更改时重新获取数据。
您的服务器页面组件:
const ServerPage = async ({
searchParams,
}: {
searchParams: Promise<{ yourSearchParam: string }>
}) => {
const { yourSearchParam } = await searchParams
console.log(yourSearchParams)
//your fetch function or DB call
return <div>May Page</div>
}