【问题标题】:react query lazy loaded properties of an object反应查询对象的延迟加载属性
【发布时间】:2022-08-13 03:02:42
【问题描述】:

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

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

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

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

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

我希望每次查询执行后,可以将结果合并到同一个缓存对象中,如果需要的属性已经存在,则直接返回缓存的结果,但是我上面的写法做不到,能否给我任何帮助?谢谢!

    标签: react-query


    【解决方案1】:

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

    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 函数将写入同一个缓存条目,从而相互覆盖。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-28
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 2014-07-26
      • 1970-01-01
      相关资源
      最近更新 更多