推荐答案
Next.js 提供了多种数据获取方式,主要包括以下几种:
getStaticProps:用于在构建时获取数据并生成静态页面。getStaticPaths:用于动态路由的页面,生成静态页面时确定所有可能的路径。getServerSideProps:用于在每次请求时获取数据并生成页面。useSWR:用于客户端数据获取,支持缓存和重新验证。useEffect+fetch:用于在客户端获取数据,适用于不需要 SEO 的场景。
本题详细解读
1. getStaticProps
getStaticProps 是 Next.js 中用于在构建时获取数据的方法。它会在构建时运行,并将获取的数据作为 props 传递给页面组件。这种方式适用于内容不经常变化的页面,比如博客文章、产品列表等。
// www.javascriptcn.com code example
export async function getStaticProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: {
data,
},
};
}2. getStaticPaths
getStaticPaths 用于动态路由的页面,通常在构建时生成所有可能的路径。它通常与 getStaticProps 一起使用,以确保每个动态路由的页面都能获取到相应的数据。
// www.javascriptcn.com code example
export async function getStaticPaths() {
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();
const paths = posts.map((post) => ({
params: { id: post.id },
}));
return { paths, fallback: false };
}3. getServerSideProps
getServerSideProps 用于在每次请求时获取数据并生成页面。这种方式适用于需要频繁更新数据的页面,比如用户仪表盘、实时数据展示等。
// www.javascriptcn.com code example
export async function getServerSideProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: {
data,
},
};
}4. useSWR
useSWR 是一个 React Hook,用于在客户端获取数据。它支持缓存和重新验证,非常适合用于需要频繁更新的数据展示。
// www.javascriptcn.com code example
import useSWR from 'swr';
function Profile() {
const { data, error } = useSWR('/api/user', fetch);
if (error) return <div>Failed to load</div>;
if (!data) return <div>Loading...</div>;
return <div>Hello, {data.name}!</div>;
}5. useEffect + fetch
useEffect 是 React 的一个 Hook,用于在组件挂载或更新时执行副作用操作。结合 fetch,可以在客户端获取数据。这种方式适用于不需要 SEO 的场景,比如用户登录后的页面。
// www.javascriptcn.com code example
import { useEffect, useState } from 'react';
function Profile() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('/api/user')
.then((res) => res.json())
.then((data) => setData(data));
}, []);
if (!data) return <div>Loading...</div>;
return <div>Hello, {data.name}!</div>;
}