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

React使用reqres接口时报TypeError: this.state.data.map错误如何解决

问题原因

  • 接口返回结构不匹配:https://jsonplaceholder.typicode.com/users 直接返回用户数组,可直接调用map方法;但https://reqres.in/api/users?page=2返回的是封装后的对象,真实用户列表存储在返回对象的data属性中,你将整个返回对象赋值给this.state.data,普通对象没有map方法,因此触发类型错误。
  • 渲染逻辑写法错误:你在render方法中用箭头函数包裹了map逻辑,但没有执行该函数,就算接口数据正确也无法正常渲染列表。

修复代码

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      isLoaded: false,
    };
  }

  componentDidMount() {
    fetch("https://reqres.in/api/users?page=2")
      .then((res) => res.json())
      .then((json) => {
        this.setState({
          isLoaded: true,
          // 取返回对象中存储用户列表的data字段赋值
          data: json.data,
        });
      });
  }

  render() {
    const { isLoaded, data } = this.state;
    if(!isLoaded){
      return <div>加载中</div>
    } else {
      return (
        <div>
          <ul>
            {/* 移除多余的箭头函数包裹,直接调用map遍历 */}
            {data.map((item, index) => (
              <li key={index}>Email: {item.email}</li>
            ))}
          </ul>
        </div>
      );
    }
  }
}

export default Home;

优化提示:列表渲染的key属性优先使用数据的唯一标识(比如本接口返回的用户id)替代索引index,可避免列表重排时出现渲染异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 14:27:02