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

React Native报错this.state.questions.map()不是函数的问题求助

解决React Native中map() is not a function & map undefined的问题

我来帮你梳理下问题的根源和解决方案:

第一个错误:this.state.questions.map() is not a function

这个错误的核心原因很简单:你把整个response.data对象赋值给了this.state.questions,而不是里面的results数组。

看你打印的响应对象,response.data的结构大概是这样的:

{
  response_code: 0,
  results: [/* 你的10个问题数组 */]
}

当你执行this.setState({ questions: response.data })时,this.state.questions变成了一个对象,而对象是没有map()方法的,自然就报错了。

第二个问题:尝试用results后出现map undefined

这大概率是因为你可能在赋值时写错了路径,或者没有处理异步请求的边界情况——组件第一次渲染时,this.state.questions还是初始的空数组,但如果赋值过程中出错(比如路径写错),它可能变成undefined,这时候调用map就会报错。

完整的解决方案

我给你修正后的代码,同时优化一些过时的写法:

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import axios from 'axios';

class QuestionList extends Component {
  state = { questions: [] };

  // 替换废弃的componentWillMount,用componentDidMount发起请求更规范
  componentDidMount() {
    axios
      .get('https://opentdb.com/api.php?amount=10&difficulty=hard&type=boolean')
      .then(response => {
        // 正确取到results数组赋值给questions
        this.setState({ questions: response.data.results });
      })
      .catch(error => {
        // 别忘了添加错误捕获,避免请求失败导致的崩溃
        console.error('请求问题列表失败:', error);
      });
  }

  renderQuestions() {
    // 先判断questions是否为数组且有内容,再执行map
    if (!Array.isArray(this.state.questions) || this.state.questions.length === 0) {
      return <Text>加载中...</Text>;
    }

    return this.state.questions.map((question, index) => {
      // 注意要给每个列表项加唯一的key,React要求
      return <Text key={index}>{question.question}</Text>;
    });
  }

  render() {
    return (
      <View>
        {this.renderQuestions()}
      </View>
    );
  }
}

export default QuestionList;

关键修改点说明:

  • 把componentWillMount换成componentDidMount:前者已经被React官方废弃,后者是发起网络请求的标准时机。
  • 正确赋值:response.data.results才是你要的问题数组,而不是response.data。
  • 边界处理:在渲染前判断数组是否有效,避免异步请求未完成时的报错,同时给用户显示加载状态。
  • 添加key:React列表渲染要求每个子元素有唯一key,这里用index作为临时方案(如果有唯一id的话用id更好)。
  • 错误捕获:添加catch块处理请求失败的情况,让程序更健壮。

这样修改后,你应该就能正常遍历问题列表了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:26:50