使用 useSWR 的 Next.js 动态页面

发布于 2025-01-12 14:14:57 字数 903 浏览 3 评论 0原文

我想使用 useSWR 和 useRouter 基于 Saloon 配置文件的 ID 创建动态页面,但数据在页面渲染后加载。

这是我的代码:

import useSWR from "swr";
import { useRouter } from "next/router";

const fetcher = (url) => fetch(url).then((res) => res.json());

export default function FindSaloonProfile() {
  const router = useRouter();
  const { id } = router.query;
  const { data, error } = useSWR(
    id ? `/api/getSaloons` : null,
    id ? fetcher : null
  );

  if (error) return <div>failed to load</div>;
  if (!data) return <div>loading...</div>;

  return <>Hello {data.name} </>;
}

如果我 console.log(data),它开始获取 undefined 并随后加载数据,但为时已晚,因为页面是已经渲染了。

console

我做错了什么?

I want to create dynamic pages based on the ID of a Saloon profile using useSWR and useRouter, but the data loads in after the pages are rendered.

This is my code:

import useSWR from "swr";
import { useRouter } from "next/router";

const fetcher = (url) => fetch(url).then((res) => res.json());

export default function FindSaloonProfile() {
  const router = useRouter();
  const { id } = router.query;
  const { data, error } = useSWR(
    id ? `/api/getSaloons` : null,
    id ? fetcher : null
  );

  if (error) return <div>failed to load</div>;
  if (!data) return <div>loading...</div>;

  return <>Hello {data.name} </>;
}

If I console.log(data), it starts getting undefined and loads in the data afterward, but then it is too late, as the page is already rendered.

console

What do I do wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

开始看清了 2025-01-19 14:14:57

将 fetcher 包装在一个函数中:

const fetcher = (url) =>
  fetch(url).then(
    async (res)=> {
      const result = await res.json();

      if (res.status !== 200) {
        return Promise.reject(result);
      } else {
        return result;
      }
    }
  );

Wrap the fetcher in a function:

const fetcher = (url) =>
  fetch(url).then(
    async (res)=> {
      const result = await res.json();

      if (res.status !== 200) {
        return Promise.reject(result);
      } else {
        return result;
      }
    }
  );
深爱不及久伴 2025-01-19 14:14:57

Next.js 是服务器端渲染框架,但大多数 SWR 仅在客户端工作,因此这意味着 API 在页面加载(或 Javascript 加载)之前不会获取数据。

最近,SWR 发布了 Next.js 集成的新文档。你可以在这里查看。

https://swr.vercel.app/docs/with-nextjs

让我试试简而言之,

getStaticProps将帮助您在服务器端获取数据

 export async function getStaticProps() {
  // `getStaticProps` is executed on the server side.
  const saloons = await getSaloons() //you can call `fetcher` here too
  return {
    props: {
      fallback: {
        '/api/getSaloons': saloons
      }
    }
  }
}

之后,您需要导入SWRConfig进行fallback这是为了获取的数据(React-Next.js Hydration 可以帮助您将数据与 React 的上下文链接起来)

export default function Page({ fallback }) {
  // SWR hooks inside the `SWRConfig` boundary will use those values.
  return (
    <SWRConfig value={{ fallback }}>
      <FindSaloonProfile />
    </SWRConfig>
  )
}

最后,您只需拥有常用的组件

import useSWR from "swr";
import { useRouter } from "next/router";

const fetcher = (url) => fetch(url).then((res) => res.json());

export default function FindSaloonProfile() {
  const router = useRouter();
  const { id } = router.query;
  //your data will get from the server initially, and then it will try to fetch again for the update
  const { data, error } = useSWR(
    id ? `/api/getSaloons` : null,
    id ? fetcher : null
  );

  if (error) return <div>failed to load</div>;
  if (!data) return <div>loading...</div>;

  return <>Hello {data.name} </>;
}

希望我的答案能够帮助您

Next.js is the server-side rendering framework, but mostly SWR works on the client-side merely, so it means API won't fetch data till the page loaded (or Javascript loaded).

Recently, SWR has published a new document for Next.js integration. You can check it out here.

https://swr.vercel.app/docs/with-nextjs

Let me try to keep it in a short explanation

getStaticProps will help you to get data on the server-side

 export async function getStaticProps() {
  // `getStaticProps` is executed on the server side.
  const saloons = await getSaloons() //you can call `fetcher` here too
  return {
    props: {
      fallback: {
        '/api/getSaloons': saloons
      }
    }
  }
}

After that, you need to import SWRConfig for fallback which is for the fetched data (React-Next.js hydration with help you to link your data with React's context)

export default function Page({ fallback }) {
  // SWR hooks inside the `SWRConfig` boundary will use those values.
  return (
    <SWRConfig value={{ fallback }}>
      <FindSaloonProfile />
    </SWRConfig>
  )
}

Lastly, you just have your usual component

import useSWR from "swr";
import { useRouter } from "next/router";

const fetcher = (url) => fetch(url).then((res) => res.json());

export default function FindSaloonProfile() {
  const router = useRouter();
  const { id } = router.query;
  //your data will get from the server initially, and then it will try to fetch again for the update
  const { data, error } = useSWR(
    id ? `/api/getSaloons` : null,
    id ? fetcher : null
  );

  if (error) return <div>failed to load</div>;
  if (!data) return <div>loading...</div>;

  return <>Hello {data.name} </>;
}

Hopefully, my answer is able to help you

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文