代码之家  ›  专栏  ›  技术社区  ›  Ofir

React query-强制查询新对象id的新数据

  •  4
  • Ofir  · 技术社区  · 1 年前

    我正在使用react查询根据博客帖子的Id获取博客帖子的数据。当我访问某个博客帖子,然后导航到另一个博客帖子时,它首先向我显示上一个博客文章的数据,然后用新信息重新呈现页面。 数据似乎首先从缓存中提取,然后刷新。

    代码:

    const BlogPost = () => {
    // Getting the blogPostId from the Url
      const { blogPostId } = useParams();
    
    // Querying the blogPostData from the server using its id. (here is the problem probably...)
      const { data: blogPostData } = useQuery<BlogPostType>({
        queryKey: ["getBlogPost"],
        queryFn: () => apiClient.getPostById(blogPostId),
      });
    
      return (
        <div>
          <h1>{blogPostData?.title}</h1>
          <hr/>
          <p>{blogPostData?.description}</p>
        </div>
      );
    };
    

    有解决办法吗?(我希望新数据能立即显示)

    1 回复  |  直到 1 年前
        1
  •  2
  •   AKX Bryan Oakley    1 年前

    博客帖子ID必须是密钥的一部分。

    const { data: blogPostData } = useQuery<BlogPostType>({
      queryKey: ["getBlogPost", blogPostId],
      queryFn: () => apiClient.getPostById(blogPostId),
    });
    

    As documented :

    当查询需要更多信息来唯一描述其数据时,您可以使用带有字符串和任意数量的可序列化对象的数组来描述它。[…]传递ID、索引或其他原语来唯一标识项目是很常见的: useQuery({ queryKey: ['todo', 5], ... })

    同样的模式也适用于 swr ,事实上与 deps 你会给的 useEffect .