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

如何在SvelteKit中获取文章数据时避免重复API调用

如何在SvelteKit中复用文章数据避免重复API调用

我正在开发一个SvelteKit应用,需要获取文章列表数据,同时要避免重复发起API请求:

  • 路由 all-posts/+page.svelte:调用 fetchAllPostsData() 获取文章列表
  • 路由 post/[id]/[title]/+page.svelte:再次调用 fetchPostDataById(id) 获取单篇文章数据并展示

目前的实现会先调用fetchAllPostsData(),进入文章详情页后又调用fetchPostDataById(id),存在效率问题。相关代码如下:

all-posts/+page.svelte 代码

<script>
    import { onMount } from 'svelte';
    import { fetchAllPostsData } from './fetch-post-data';

    let postsDataArr = [];

    onMount(async () => {
        postsDataArr = await fetchAllPostsData();
    });
</script>

<section>
    <ul>
        {#each postsDataArr as post}
            <li><a href={`/post/${post.id}/${post.title.replace(/[\s ]/g, '-')}`}>{post.title}</a></li>
        {/each}
    </ul>
</section>

post/[id]/[title]/+page.svelte 代码

<script>
    import { onMount } from 'svelte';
    import { page } from '$app/stores';
    import { fetchPostDataById } from '../fetch-post-data';

    let id;
    /**
     * @type {any}
     */
    let data;

    $: id = $page.params.id;

    onMount(async () => {
        data = await fetchPostDataById(id);
    });
</script>

<section>
    {#if data}
    <div>
        <div>{@html data.html}</div>
    </div>
    {/if}
</section>

补充说明

不能完全移除fetchPostDataById(id),因为用户直接访问文章分享链接时,需要通过这个方法获取数据来确保内容正确展示。

问题

怎么重构代码避免两次API调用?只获取一次文章列表,在两个路由里复用数据。


采纳建议后的更新

目前已经改用Svelte的TanStack Query替代直接调用API,代码如下:

<script lang="ts">
  import { createQuery } from '@tanstack/svelte-query';

  // 定义请求选项
  const options = {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({"limit":100})
  };

  // 获取分页文章的请求函数
  const fetchPaginatedPosts = async () => {
    try {
      const response = await fetch('http://localhost:4000/get-paginated-posts', options);
      if (!response.ok) {
        throw new Error('网络请求失败');
      }
        const res = await response.json()
        console.log(res)

          /*
            res = {
              "posts": [
                  {
                      "id": "667776bcc5d22d6226f7647b",
                      "description": "Hello, this is me!",
                      "title": "My page is here!",
                      "update_count": 0,
                      "updated_at": "2024-06-23T10:13:32.190+00:00",
                      "created_at": "2024-06-23T10:13:32.190+00:00",
                      "created_by": "666ff11d406248baf2e87df4",
                  }, {...}
              ],
              "nextToken": "667776bcc5d22d6226f7647b"
          }
          */
         
        return res;
    } catch (error) {
      console.error(error);
      throw error;
    }
  };

  // 创建查询实例
  const query = createQuery({
    queryKey: ['posts'],
    queryFn: fetchPaginatedPosts,
    initialData: null,
  });

  // 获取并打印文章数据
  const result = $query.data;
  console.log({result});
</script>

<!-- HTML 部分省略 -->

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 05:25:58