我需要在我的组件中过滤电影。初始查询必须是所有电影。在我单击按钮(按钮名称例如历史/喜剧)后,我在 react 组件中呈现的数据必须更改为仅包含历史或喜剧电影的此类查询的数据。我如何在react-query中实现这一点。
最佳答案
理想情况下,过滤应该在后端进行。这样,您只需将过滤后的电影的名称作为查询键的一部分即可。如果键发生变化,React Query 将自动重新获取,并且还会单独缓存每个条目过滤:
const [name, setName] = React.useState()
const { data } = useQuery(['movies', name], () => fetchMovies(name)))
如果后端不做过滤,可以直接对useQuery返回的数据进行过滤:
const [name, setName] = React.useState()
const { data } = useQuery(['movies'], () => fetchMovies()))
const result = filterByName(data, name)
这很适合自定义 Hook 。
如果需要引用稳定性,可以将结果创建包装在useMemo
中:
const result = React.useMemo(() => filterByName(data, name), [data, name])
您还可以利用react-query的select
选项:
const [name, setName] = React.useState()
const { data } = useQuery(
['movies'],
() => fetchMovies()),
{
select: (response) => filterByName(response, name)
}
)
在这种情况下,从 useQuery
返回的数据
已经被过滤了,你不必担心内存。
关于reactjs - 在react-query中过滤数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70904680/