gpt4 book ai didi

How to fetch data server-side in the latest Next.js? Tried getStaticProps but it's not running and getting undefined(如何在最新的Next.js中获取服务器端数据?尝试getStaticProps,但它不运行,并且未定义)

转载 作者:bug小助手 更新时间:2023-10-25 15:11:10 25 4
gpt4 key购买 nike



I am working on a Django Rest Framework with Next.js, and I am getting stuck with fetching data from the API. I have data in this url http://127.0.0.1:8000/api/campaigns and when I visit the url I see the data.

我正在使用Next.js开发一个Django REST框架,但我遇到了从API获取数据的问题。我在这个URL http://127.0.0.1:8000/api/campaigns中有数据,当我访问该URL时,我会看到这些数据。


The problem is when I fetch and console the data with Next.js, I get undefined. Also when I try mapping the data, I get the error:

问题是,当我使用Next.js获取和控制数据时,我得不到定义。另外,当我尝试映射数据时,我得到错误:



Unhandled Runtime Error


Error: Cannot read properties of undefined (reading 'map')



Here is my Index.js file where the data fetching is done:

下面是我的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
},
}
}

Here is a screenshot of the data I am getting when I visit the URL:

以下是我访问URL时获得的数据的屏幕截图:


Image


Here is the file structure for the Next.js app inside the front end:

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


File Structure


Also, note that I am using the latest version of Next.js. Any help will be highly appreciated. Thanks.

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


更多回答

what do u get here const data = await response.json(); console.log(data)

您在这里得到了什么const data=等待响应.json();console.log(Data)

Can you show your file structure? And where in your folder is the component you have shown?

你能展示一下你的文件结构吗?您所显示的组件在文件夹中的什么位置?

@Yilmaz console.log(data) returns nothing

@Yilmaz console.log(Data)不返回任何内容

@YoussoufOumar I just edited it and added the screenshot. Thanks

@YoussoufOumar我只是编辑了它并添加了截图。谢谢

优秀答案推荐

Methods like getServerSideProps and getStaticProps are for fetching data on the server but they only work for page components inside the pages folder (the initial way of setting up routes in Next.js).

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


Since Next.js 13, in the app directory (used when you answer yes to the last question shown in the below image) we have Server Components, where you can fetch data directly in the component body as shown in the below code snippet (please read the comments):

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


enter image description here


/*
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 "...";
}

That has been said, you can get data without fetch(), using any library, or even directly talking to your database with an ORM, in which case you can use Route Segment Config:

也就是说,您可以在不使用FETCH()、使用任何库、甚至使用ORM直接与数据库对话的情况下获取数据,在这种情况下,您可以使用路由段配置:


// 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();
// ...
}


In app directory you cannot use getServerSideProps, getStaticProps,getInitialProps like methods for data fetching. Instead of this with server component you can make component it self async and fetch data in component body direclty. Futhur more you can pass the data to client compoent for rendering service.

在app目录中,您不能使用getServerSideProps、getStaticProps、getInitialProps之类的方法获取数据。而不是使用服务器组件,您可以使组件自同步,并在组件主体目录中获取数据。此外,您还可以将数据传递给客户端组件以提供服务。


export async function getData(){
const res = await fetchData();
const data = res.json()
return data

} }

Now you can call this async function in your main component

现在,您可以在主组件中调用此异步函数


export async function(){
const data =await getData()
return (<ClientComponent data />)
}


This StackOverFlow question (Can't use GetStaticProp in Next.js 13) was closed as a duplicate of this question.

此StackOverflow问题(无法在Next.js 13中使用GetStaticProp)已作为此问题的副本关闭。


To help rookies like me:

为了帮助像我这样的新手:


You can't use getStaticProps in Nextjs 13 (using App Router).

您不能在Nextjs 13中使用getStaticProps(使用App Router)。


The new way is to just use fetch. You can read more about fetch here.

新的方法是只使用FETCH。你可以在这里阅读更多关于Fetch的内容。


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

This image compares the old and new way of doing things. image source

这张图片对比了新旧的做事方式。图像源


enter image description here


Because the new default is to cache all fetch requests (unless they opt out) calling fetch in a static component has the same effect as getStaticProps. You can read more about Static Data Fetching here.

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


So to be clear this normal fetch request:

因此,为了明确这一正常的获取请求:


//Similar to 'getStaticProps' when used in a static rendering component
fetch(API_URL)

is the same as this 'force-cache' request:

与此‘强制缓存’请求相同:


//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' })

More info about the default caching here.

有关默认缓存的更多信息,请点击此处。


Why did you want to use getStaticProps in the first place?

为什么首先要使用getStaticProps?


To help the rookies, who find getStaticProps in a tutorial and find there way here, the reason you want to use getStaticProps is you want to render a page once, and then send that page to every user.

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


This makes your page faster, send less code to your users, and is better for SEO etc.

这使得你的页面更快,发送给你的用户的代码更少,而且对SEO等更好。


But what if you need to get some data to render that page once? Before Nextjs 13 you would use getStaticProps.

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


Now you fetch in a static component. The effect is the same.

现在,您将获取一个静态组件。效果是一样的。


And that effect is, once (at build time when you deploy your project) Nextjs will go get some data, then use that data to render a page, and then send that pre-rendered page to everyone who needs it.

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


If you need to statically generate a bunch of pages using dynamic routes, the generateStaticParams function can be used to generate routes at build time instead of on-demand at request time for dynamic routes. info here.

如果您需要使用动态路由静态生成一系列页面,则可以使用genateStaticParams函数在构建时生成路由,而不是在动态路由的请求时按需生成。信息请点击此处。


For rookies, if you don't know what dynamic routes are, just use fetch. :)

对于新手来说,如果你不知道什么是动态路由,只需使用FETCH。:)


更多回答

How are we supposed to manage global state from the data we fetched using async functions (new method of using SSG) ?

我们应该如何从使用异步函数(使用SSG的新方法)获取的数据中管理全局状态?

Hi Sebak! The answer in this thread go trough that.

嗨,塞巴克!这条帖子中的答案就是这样的。

How do we manage global states of the data we fetched using SSG or SSR?

我们如何管理使用SSG或SSR获取的数据的全局状态?

Since next js has caching features. Does that mean we don't have to use libraries like react query ?

因为Next JS具有缓存功能。这是否意味着我们不必使用像Reaction Query这样的库?

@SebakThapa Depends but you might now. React Query does other things besides just fetching but this blog post might help give you more details - tkdodo.eu/blog/you-might-not-need-react-query

@SebakThapa视情况而定,但你现在可能会。除了抓取之外,Reaction查询还可以做其他事情,但这篇博客文章可能会帮助您提供更多详细信息-tkdodo.eu/blog/you-May-not-Need-reaction-Query

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com