You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用GROQ查询Sanity的下一篇文章?当前nextPost返回null

问题原因

你的nextPost返回null的核心问题是并行请求导致上下文引用失效:

  • 你通过Promise.all同时发起当前文章和下一篇文章的请求,两个请求完全独立,nextPost查询中的^._createdAt无法获取到当前文章的创建时间(^仅能在嵌套查询或同一请求的上下文里生效),导致过滤条件失效,自然拿不到结果。
修复方案

先获取当前文章的_createdAt,再将该值作为参数查询下一篇文章,避免并行请求。修改后的函数如下:

export async function getPostAndMorePosts(slug, preview) {
  const curClient = getClient(preview);
  
  // 先获取当前文章详情
  const post = await curClient.fetch(
    `*[_type == "project" && slug.current == $slug] | order(_createdAt desc) {
      _createdAt,
      'slug': slug.current,
    }`,
    { slug }
  ).then(res => res?.[0]);

  // 基于当前文章的创建时间查询下一篇(创建时间晚于当前的最早文章)
  let nextPost = null;
  if (post?._createdAt) {
    nextPost = await curClient.fetch(
      `*[_type == "project" && _createdAt > $currentCreatedAt] | order(_createdAt asc)[0] {
        _createdAt,
        'slug': slug.current,
      }`,
      { currentCreatedAt: post._createdAt }
    );
  }

  return { post, nextPost };
}
额外调整说明
  • 若你需要的“下一篇”是创建时间更早的文章,只需将查询条件改为_createdAt < $currentCreatedAt,同时排序改为order(_createdAt desc)[0]。
  • 确保_createdAt为标准ISO日期格式,Sanity默认生成的该字段符合要求,无需额外处理。

内容的提问来源于stack exchange,提问作者Burger Sasha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 23:30:18