首页 > 解决方案 > TypeError:无法读取 React 未定义的属性“标题”

问题描述

我试图从应用程序组件中的状态访问数组,但我不知道为什么它不起作用

import React from "react";
import "./App.css";
//import Category from "./components/Category";

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      categories: [],
    };
  }

  componentDidMount() {
    //const addon = Math.floor(Math.random() * 1000);
    fetch("http://jservice.io/api/categories?count=5")
      .then((response) => response.json())
      .then((data) => {
        var arr = [];
        for (var x in data) {
          console.log(arr.push(data[x]));
          console.log(data[x]);
        }
        this.setState({
          categories: arr,
        });
      });
  }

  render() {
    return <div>{this.state.categories[0].title}</div>;
  }
}

export default App;

对于上下文,这是我从 API 获得的 JSON

[{"id":11531,"title":"mixed bag","clues_count":5},{"id":11532,"title":"let's \"ch\"at","clues_count":5},{"id":5412,"title":"prehistoric times","clues_count":10},{"id":11496,"title":"acting families","clues_count":5},{"id":11498,"title":"world city walk","clues_count":5}]

似乎每个对象都应该有一个标题,但 js 另有说明

标签: javascripthtmlarraysreactjsapi

解决方案


当应用程序第一次加载时,它还没有来自 API 的内容,因此您尝试访问空数组的第一个元素。因此,即使 API 调用很快,也总会有一种状态是该categories数组为空。所以在render方法中,你需要检查数组是否有一些值。

render() {
    if (this.state.categories.length === 0) {
        return <div>No categories</div>
    }
    return <div>{this.state.categories[0].title}</div>;
  }

推荐阅读