You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js获取的数据无法在DOM中显示问题求助

问题原因及解决办法

你遇到的问题是randomuser.me API的返回数据结构和你访问的路径不匹配。该接口返回的JSON结构里,gender字段并不直接在data根对象下,而是嵌套在results数组的第一个元素中,这就是为什么你能通过console.log看到数据,但DOM里无法渲染出内容的核心原因。

修正后的代码示例

写法一(无类型定义)

export default async function links(){
    const res = await fetch('https://randomuser.me/api/');
    const data = await res.json();
    // 从results数组中取出第一个用户数据
    const user = data.results[0];
    return(
      <>
        <h1>{user.gender}</h1>
        <p>邮箱:{user.email}</p>
      </>
    )
}

写法二(带TypeScript类型)

// 调整类型定义以匹配API实际返回结构
type User = {
    gender: string;
    email: string;
    phone: string; // 注意:API返回的phone是带格式的字符串,不是数字类型
}

type ApiResponse = {
    results: User[];
}

export default async function links(){
    const res = await fetch('https://randomuser.me/api/');
    const data: ApiResponse = await res.json();
    const user = data.results[0];
    return(
      <>
        <h1>{user.gender}</h1>
        <p>邮箱:{user.email}</p>
        <p>电话:{user.phone}</p>
      </>
    )
}

额外说明:原写法二中将phone定义为number类型是错误的,randomuser.me返回的电话字段是带括号、短横线的格式化字符串,需要将类型改为string才能避免类型校验报错。

内容的提问来源于stack exchange,提问作者Christ Oscar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 03:04:56