我正在使用 Next.js 开发 Django Rest 框架,但我在从 API 获取数据方面遇到了困难。我在这个网址中有数据
http://127.0.0.1:8000/api/campaigns
,当我访问该网址时,我看到了数据。
问题是当我使用 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
},
}
}
这是我访问该 URL 时获取的数据的屏幕截图:
这是前端内 Next.js 应用程序的文件结构:
另请注意,我使用的是最新版本的 Next.js。任何帮助将不胜感激。谢谢。
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";
/*
Depending on whether you are using dynamic routes or not, and the `cache`
option of `fetch`, you can mimic previous methods
like getStaticProps or getServerSideProps.
*/
async function getCampaigns() {
const response = await fetch("http://127.0.0.1:8000/api/campaigns", { cache: "no-store" });
const data = await response.json();
return data;
}
/*
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`.
You can pass them to your data fetching function.
*/
export default async function Index({ params, searchParams }) {
const data = await getCampaigns();
return <div>{/* You can use data here. */}</div>;
}
了解更多,您可以阅读App Router增量采用指南。
在应用程序目录中,您不能使用 getServerSideProps、getStaticProps、getInitialProps 之类的方法来获取数据。您可以将组件设置为自异步并直接在组件主体中获取数据,而不是使用服务器组件。未来您还可以将数据传递到客户端组件以进行渲染服务。
export async function getData(){
const res = await fetchData();
const data = res.json()
return data
} }
现在你可以在主组件中调用这个异步函数了
export async function(){
const data =await getData()
return (<ClientComponent data />)
}
此 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()
}
这张图片比较了新旧的做事方式。 图片来源
因为新的默认设置是缓存所有 fetch 请求(除非他们选择退出),所以在静态组件中调用 fetch 具有与
getStaticProps
相同的效果。您可以在此处阅读有关静态数据获取的更多信息。
所以要清楚这个正常的获取请求:
//Similar to 'getStaticProps' when used in a static rendering component
fetch(API_URL)
与此“强制缓存”请求相同:
//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' })
有关 默认缓存的更多信息请参见此处。
你为什么要首先使用 getStaticProps?
为了帮助那些在教程中找到
getStaticProps
并在这里找到方法的新手,您想要使用 getStaticProps
的原因是您想要渲染一次页面,然后将该页面发送给每个用户。
这会使您的页面更快,向用户发送更少的代码,并且更有利于 SEO 等。
但是如果您需要获取一些数据来渲染该页面一次怎么办?在 Nextjs 13 之前,您将使用
getStaticProps
。
现在您
fetch
处于静态组件中。效果是一样的。
效果是,一旦(在部署项目时的构建时)Nextjs 将获取一些数据,然后使用该数据渲染页面,然后将该预渲染页面发送给每个需要它的人。
如果需要使用动态路由静态生成一堆页面,可以使用
generateStaticParams
函数在构建时生成路由,而不是在请求时按需生成动态路由。 信息在这里。
对于菜鸟来说,如果你不知道什么是动态路由,就用
fetch
。 :)