如何在最新的Next.js中获取服务器端数据?尝试了 getStaticProps 但它没有运行并且未定义

vic*_*tor 17 javascript django rest reactjs next.js

我正在使用 Next.js 开发 Django Rest 框架,但我陷入了从 API 获取数据的困境。我在这个 url 中有数据http://127.0.0.1:8000/api/campaigns,当我访问该 url 时,我会看到数据。

问题是当我使用 Next.js 获取并控制台数据时,我得到了undefined. 另外,当我尝试映射数据时,我收到错误:

未处理的运行时错误

错误:无法读取未定义的属性(读取“地图”)

这是我Index.js完成数据获取的文件:

import React from 'react'

export default function Index ({data}) {
  console.log(data)
  return (
    <div>
      <main>
        <h1>Available Campaigns</h1>
        {data.map((element) => <div key={element.slug}>
          <div>
            <div>
              <img src={element.logo} height={120} width={100} alt="image" />
            </div>
            <div></div>
          </div>

        </div>)}
      </main>
    </div>
  );
}

export async function getStaticProps() {
  const response = await fetch("http://127.0.0.1:8000/api/campaigns");
  const data = await response.json();
  return {
    props: {
      data: data
    },
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我访问该 URL 时获取的数据的屏幕截图:

图像

以下是前端内 Next.js 应用程序的文件结构:

文件结构

另请注意,我使用的是最新版本的 Next.js。任何帮助将不胜感激。谢谢。

You*_*mar 16

getServerSideProps和 等方法getStaticProps用于在服务器上获取数据,但它们仅适用于pages文件夹内的页面组件(在 Next.js 中设置路由的初始方法)。

从 Next.js 13 开始,在app目录中(当您对下图所示的最后一个问题回答“是”时使用)我们有Server Components,您可以在其中直接在组件主体中获取数据,如下面的代码片段所示(请阅读评论):

在此输入图像描述

/*
  If you want to access headers or cookies while fetching data,
  you can use these functions:
*/
import { cookies, headers } from "next/headers";

/*
 If the below component is the default export of a `page.js` and you are using 
 dynamic routes, slugs will be passed as part of `params`, and 
 query strings are passed as part of `searchParams`.
*/
export default async function Component({ params, searchParams }) {
  /* 
    This request should be cached until manually invalidated.
    Similar to `getStaticProps`.
    `force-cache` is the default and can be omitted.
  */
  const staticData = await fetch(`https://...`, { cache: "force-cache" });

  /*
    This request should be refetched on every request.
    Similar to `getServerSideProps`.
  */
  const dynamicData = await fetch(`https://...`, { cache: "no-store" });

  /* 
    This request should be cached with a lifetime of 10 seconds.
    Similar to `getStaticProps` with the `revalidate` option.
  */
  const revalidatedData = await fetch(`https://...`, {
    next: { revalidate: 10 },
  });

  return "...";
}
Run Code Online (Sandbox Code Playgroud)

也就是说,您可以在不fetch()使用任何库的情况下获取数据,甚至可以直接使用 ORM 与数据库对话,在这种情况下您可以使用Route Segment Config

// layout.js OR page.js OR route.js 

import prisma from "./lib/prisma";

/*
  Keep one of the possibilities shown below (there are more on the doc), 
  depending on your needs. 
*/

export const revalidate = 10; // If you want to revalidate every 10s
// OR
export const dynamic = "force-dynamic"; // If you want no caching at all
// ...

async function getPosts() {
  const posts = await prisma.post.findMany();
  return posts;
}

export default async function Page() {
  const posts = await getPosts();
  // ...
}
Run Code Online (Sandbox Code Playgroud)


Jos*_*nce 8

此 StackOverFlow 问题(Can't use GetStaticProp in Next.js 13)已作为此问题的重复项关闭。

为了帮助像我这样的菜鸟:

您无法在 Nextjs 13 中使用 getStaticProps(使用 App Router)。

新的方法是只使用 fetch。您可以在此处阅读有关fetch 的更多信息。

async function getArtist(username: string) {
  const res = await fetch(`https://api.example.com/artist/${username}`)
  return res.json()
}
Run Code Online (Sandbox Code Playgroud)

这张图片比较了新旧的做事方式。图片来源

在此输入图像描述

因为新的默认设置是缓存所有 fetch 请求(除非它们选择退出),在静态组件中调用 fetch 与getStaticProps. 您可以在此处阅读有关静态数据获取的更多信息。

所以要清楚这个正常的获取请求:

//Similar to 'getStaticProps' when used in a static rendering component
fetch(API_URL)
Run Code Online (Sandbox Code Playgroud)

与此“强制缓存”请求相同:

//This request would be cached until manually invalidated. 
//Similar to 'getStaticProps'
//Use this type of fetching for data that does not change often.
 
fetch(API_URL, { cache: 'force-cache' })
Run Code Online (Sandbox Code Playgroud)

有关默认缓存的更多信息请参见此处

您首先为什么要使用 getStaticProps?

为了帮助新手,他们getStaticProps在教程中找到并在这里找到方法,您想要使用的原因getStaticProps是您想要渲染一次页面,然后将该页面发送给每个用户。

这使您的页面速度更快,向用户发送的代码更少,并且更有利于 SEO 等。

但是,如果您需要获取一些数据来渲染该页面一次怎么办?在 Nextjs 13 之前,您将使用getStaticProps.

现在您fetch处于静态组件中。效果是一样的。

其效果是,一旦(在部署项目时的构建时)Nextjs 将获取一些数据,然后使用该数据渲染页面,然后将该预渲染页面发送给每个需要它的人。

如果需要使用动态路由静态生成一堆页面,则generateStaticParams可以使用该函数在构建时生成路由,而不是在请求时按需生成动态路由。信息在这里

对于菜鸟来说,如果不知道什么是动态路由,就用fetch. :)