react查询对象的延迟加载属性



我有一个api,它返回我需要的属性,如下所示:

fetchPost(1, ['title', 'content'])
// => { id: 1, title: 'hello', content: 'world!' }
fetchPost(1, ['title', 'author'])
// => { id: 1, title: 'hello', author: 'A' }

我为react查询定义了两个钩子:

function usePostTitleAndContent(id) {
return useQuery(['post', id], async () => fetchPost(id, ['title', 'content']))
}
function usePostTitleAndAuthor(id) {
return useQuery(['post', id], async () => fetchPost(id, ['title', 'author']))
}

我希望在执行完每个查询后,可以将结果合并到同一个缓存对象中,如果所需的属性已经存在,则会直接返回缓存的结果,但我上面的编写方法无法做到这一点,你能给我什么帮助吗?谢谢

返回不同数据的不同查询函数应该具有不同的键。在你的情况下,这将是:

function usePostTitleAndContent(id) {
return useQuery(['post', id, 'content'], async () => fetchPost(id, ['title', 'content']))
}
function usePostTitleAndAuthor(id) {
return useQuery(['post', id, 'author'], async () => fetchPost(id, ['title', 'author']))
}

否则,两个fetch函数将写入同一个缓存条目,从而相互覆盖。

最新更新