为何遵循Unsplash API文档仍反复获取同一图片?
问题:Unsplash API重复返回同一张图片,无API调用记录
我在Next.js应用中调用Unsplash随机图片API,每次刷新页面都得到同一张图。直接在浏览器地址栏调用该API能正常返回不同的随机JSON数据,但我的应用似乎并未发起新请求——Unsplash的API调用记录里找不到相关请求。
使用的请求代码:const response = await fetch("https://api.unsplash.com/photos/random?client_id=" + process.env.UNSPLASH_ACCESS_KEY)
完整页面代码:
import Image from "next/image"; import { UnsplashImage } from "@/models/unsplash-image"; import Link from "next/link"; export default async function Page(){ const response = await fetch("https://api.unsplash.com/photos/random?client_id=" + process.env.UNSPLASH_ACCESS_KEY) const image: UnsplashImage = await response.json(); const width = Math.min(500, image.width); const height = (width / image.width) + image.height; return( <div className="d-flex flex-column align-items-cente "> <Image src={image.urls.raw} width={width} height={height} alt={image.description} className="rounded shadow mw-100 h-100" /> by <Link href={"/users/" + image.user.username}> {image.user.username} </Link> </div> ) }
解决方案
核心原因
Next.js App Router中,页面组件内的fetch请求默认会被静态缓存——首次请求后结果会存在服务器,后续访问直接返回缓存内容,不会再调用Unsplash API,这就是为什么你看不到新的API调用记录,且图片一直重复。
解决方法
方法1:禁用单请求缓存
在fetch中添加cache: 'no-store'配置,强制每次请求都调用API:
const response = await fetch( "https://api.unsplash.com/photos/random?client_id=" + process.env.UNSPLASH_ACCESS_KEY, { cache: 'no-store' } )
方法2:强制页面动态渲染
在页面组件顶部添加export const dynamic = 'force-dynamic',让整个页面每次请求都重新渲染,自然会触发新的API调用:
import Image from "next/image"; import { UnsplashImage } from "@/models/unsplash-image"; import Link from "next/link"; // 强制页面动态渲染 export const dynamic = 'force-dynamic'; export default async function Page(){ const response = await fetch("https://api.unsplash.com/photos/random?client_id=" + process.env.UNSPLASH_ACCESS_KEY) const image: UnsplashImage = await response.json(); const width = Math.min(500, image.width); const height = (width / image.width) * image.height; // 修正高度计算错误 return( <div className="d-flex flex-column align-items-center "> {/* 修正类名拼写错误 */} <Image src={image.urls.raw} width={width} height={height} alt={image.description} className="rounded shadow mw-100 h-100" /> by <Link href={"/users/" + image.user.username}> {image.user.username} </Link> </div> ) }
额外修正提示
- 高度计算公式错误:原代码用
+会导致高度异常,应改为*来保持图片比例 - 类名拼写错误:
align-items-cente应改为align-items-center,否则布局样式不生效
内容的提问来源于stack exchange,提问作者4ztech
相关产品推荐
相关产品推荐

