【问题标题】:TypeError: Cannot read property 'title' of undefined for ReactTypeError:无法读取 React 未定义的属性“标题”
【发布时间】:2020-12-05 08:41:59
【问题描述】:

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

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 另有说明

【问题讨论】:

    标签: javascript html arrays reactjs api


    【解决方案1】:

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

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

    【讨论】:

    • componentDidMount() 在 render() 之前发生,不是吗?编辑:刚刚试了一下,它奏效了!非常感谢!
    • 是的,但是 fetch 是异步的,总是会花费更多时间(考虑网络慢,甚至请求失败)
    【解决方案2】:
    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) => {
            let arr = Object.assign([], this.state.categories);
            arr = data;
            //the `data` you are getting is in an array.
            this.setState({
              categories: arr,
            });
          });
      }
    
      render() {
        return <div>{this.state.categories && this.state.categories[0] && this.state.categories[0].title}</div>;
      }
    }
    
    export default App;
    

    组件渲染时,此时state中的categories数组为空。它试图在一个空数组中找到title 键。这就是它抛出错误的原因。 请务必检查条件

    【讨论】:

      【解决方案3】:

      当您在这里进行网络调用并获取数据时,这将是一个副作用(异步调用)。所以 React 生命周期从 componentDidMount() -> render() 开始,所以同时this.state.categories 的长度为 0,因为你用一个空数组初始化它。

      为避免此类错误,最好进行条件渲染,例如如果数组不为空,则仅渲染所需的标题。

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

      【讨论】:

        猜你喜欢
        • 2021-09-04
        • 2019-12-05
        • 2021-09-04
        • 1970-01-01
        • 2020-09-12
        • 2021-02-15
        • 2023-04-01
        相关资源
        最近更新 更多