面试题答案
一键面试1. 数据获取方案
基本不变的商品信息
使用 getStaticProps
获取商品的基本不变信息,如名称、描述。因为这些信息变动不频繁,getStaticProps
会在构建时运行,生成静态 HTML 文件,这样可以提高页面的加载性能。
示例代码:
export async function getStaticProps(context) {
const productId = context.query.productId;
const res = await fetch(`https://api.example.com/products/${productId}`);
const product = await res.json();
return {
props: {
productInfo: {
name: product.name,
description: product.description
}
},
revalidate: 60 * 60 * 24 // 每天重新验证一次,处理缓存一致性
};
}
const ProductPage = ({ productInfo }) => {
return (
<div>
<h1>{productInfo.name}</h1>
<p>{productInfo.description}</p>
</div>
);
};
export default ProductPage;
实时库存数量
使用 getServerSideProps
获取实时库存数量。因为库存数量实时变化,getServerSideProps
会在每次请求页面时运行,确保获取到最新的数据。
示例代码:
export async function getServerSideProps(context) {
const productId = context.query.productId;
const res = await fetch(`https://api.example.com/products/${productId}/stock`);
const stock = await res.json();
return {
props: {
stockQuantity: stock.quantity
}
};
}
const ProductPage = ({ stockQuantity }) => {
return (
<div>
<p>库存数量: {stockQuantity}</p>
</div>
);
};
export default ProductPage;
2. 缓存一致性问题处理
基本不变信息的缓存一致性
通过在 getStaticProps
中设置 revalidate
参数,Next.js 会在指定时间间隔(以秒为单位)后重新验证数据。例如设置 revalidate: 60 * 60 * 24
,表示每天重新验证一次数据,确保商品基本信息在一定时间内保持最新。如果在重新验证期间数据发生了重大变化,可以手动触发重新构建。
实时库存数量不存在缓存一致性问题
因为 getServerSideProps
每次请求页面时都会获取最新数据,所以不存在缓存一致性问题。但要注意这种方式对服务器压力相对较大,可通过优化 API 性能、适当缓存 API 数据等方式来缓解服务器压力。