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

React调用API无法获取数据且无报错,代码问题排查求助

你的代码存在三处核心问题,对应修改即可正常运行:

1. 接口返回字段匹配错误

你调用的宝可梦API返回的列表字段为results而非items,你写的items: result.items会给state的items赋值为undefined,自然遍历不到任何内容。

2. key属性使用错误

首先,React要求map遍历生成的元素列表,必须给最外层的遍历元素绑定唯一key,你现在把key写到了内层的p标签上,位置错误;其次接口返回的单条宝可梦数据没有id字段,item.id取到的是undefined,会触发key无效的控制台警告。

3. 错误捕获范围不全

你用then的第二个回调做错误处理,只能捕获请求阶段的网络异常,代码逻辑错误(比如字段取值错误、渲染错误)属于运行时异常,不会被这个回调捕获,所以你看不到自定义的错误提示,只能在控制台看到报错。

修正后的完整代码如下:

import React, {Component} from "react";

class PokemonList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: [],
    };
  }

  componentDidMount() {
    fetch('https://pokeapi.co/api/v2/pokemon?limit=20')
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            // 修正列表字段为results
            items: result.results
          });
        },
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
      // 补充catch捕获运行时异常
      .catch(err => {
        this.setState({
          isLoaded: true,
          error: err
        })
      })
  }
  render() {
    const { error,isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <ul>
          {items.map(item => (
            // key绑定到最外层li,用唯一的name作为key值
            <li key={item.name}>
              <p>{item.name}</p>
            </li>
          ))}
        </ul>
      );
    }
  }
}
export default PokemonList;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 21:24:03