【问题标题】:Cannot read the property of undefined map无法读取未定义地图的属性
【发布时间】:2026-02-19 18:05:01
【问题描述】:
import React from 'react';
import { Card, Text } from "react-native-paper";
import {
  SafeAreaView,
} from "react-native";

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

  // Function to collect data
  async componentDidMount() {
    await fetch(
      "https://hacker-news.firebaseio.com/v0/item/26061935.json?print=pretty"
    )
      .then((res) => res.json())
      .then((json) => {
        this.setState({
          isLoaded: true,
          data: json.data,
          
        });
        console.log("Json", JSON.stringify(json));
      });
  }

    
  render() {
    return (
      <SafeAreaView>
          <Card>
        {this.state.newdata.map((item) => {
         <Text>{item.title}</Text>
  })}
  </Card>
      </SafeAreaView>
    );
  }
}

export default Hnews;

我正在做一个黑客新闻克隆,我正在获取 API 并显示它,但给出了错误“无法读取未定义的属性(读取 'map')”。我已经看到了很多此类问题的答案,并更改了我的解决方案,但没有任何效果。

【问题讨论】:

  • 什么时候调用 someMethod ?
  • 我做了console.log,它什么也没给我。我删除了它。更新了帖子。

标签: javascript arrays reactjs react-native api


【解决方案1】:

正如我从this.state.newdata.map((item) 看到的那样,您正在尝试映射this.state.newdata,如果您注意,您正在通过调用您从未在应用程序中调用过的someMethod 将数据存储到newdata 状态,所以总是newdata 状态将为空,以下应该会为您修复它:

import React from 'react';
import { Card, Text } from "react-native-paper";
import {
  SafeAreaView,
} from "react-native";

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

  // Function to collect data
  async componentDidMount() {
    await fetch(
      "https://hacker-news.firebaseio.com/v0/item/26061935.json?print=pretty"
    )
      .then((res) => res.json())
      .then((json) => {
        this.setState({
          isLoaded: true,
          data: json.data,
          
        });
        console.log("Json", JSON.stringify(json));
      });
  }

    
  render() {
    return (
      <SafeAreaView>
          <Card>
        {this.state.data.map((item) => {
         <Text>{item.title}</Text>
  })}
  </Card>
      </SafeAreaView>
    );
  }
}

export default Hnews;

如果你注意你正在获取的数据,你会明白那里没有可映射的项目,你只能映射到kids

【讨论】:

  • 更新了帖子。
  • 更新了答案@Gaurav
【解决方案2】:

您的代码 sn-p 似乎不完整。但是,如果您的函数 someMethod 在任何地方的代码中被调用,它可能是罪魁祸首。

在其中,您将状态的 newdata 字段设置为字符串,方法是为其分配 JSON.stringify 输出。一旦它是一个字符串,就没有映射函数可以调用它,我假设这就是你得到未定义错误的原因。必须是数组才能使用map函数。

如果您完全删除 newdata 并且仅引用数据,它应该可以工作,假设响应数据是一个数组。

【讨论】:

  • 前段时间更新了代码
最近更新 更多