首页 > 解决方案 > ReactJS:从 JSON 文件中提取数据时出错

问题描述

我正在尝试将数据从我的 JSON 文件传递​​到我的 ReactJS 应用程序,但收到以下错误:

TypeError:无法读取'mainPage'未定义的属性

如果我尝试siteData仅使用 console.log,它将运行良好。我猜这个问题可能与访问对象参数有关

你能告诉我我做错了什么吗?

这是我的 JSON 对象:

{
    "data": {
        "mainPage": {
            "navBar": ["HR", "HR1", "HR2"],
            "name": "Name one",
            "agency": "agency one"
        },

        "secondPage": {
            "rank": 2,
            "name": "Name Two",
            "agency": "agency two"
        },

        "thirdPage": {
            "rank": 3,
            "name": "Name Three",
            "agency": "agency three"
        }
    }
}

我的 .jsx 文件:

import React from 'react';
import axios from 'axios';
import logo from '../img/company_logo.png';
import '../css/header.scss';

export default class Header extends React.Component {
  constructor() {
    super();
    this.state = {
      siteData: {},
    };
  }

  componentDidMount() {
    axios.get('./data.json')
      .then((res) => {
        this.setState({
          siteData: res.data,
        });
      })
      .catch((err) => {
        console.log(err);
      });
  }

  render() {
    // console.log(this.state);
    const { siteData } = this.state;
    console.log(siteData.data.mainPage);

    return (
      <div className="headerWrapper">
        <a href=".../public/index.html">
        <img src={logo} alt="company_logo" id="companyLogo" />
        </a>
        <ul>
          <li>Navbar_1</li>
          <li>Navbar_2</li>
          <li>Navbar_3</li>
        </ul>
      </div>
    );
  }
}

标签: javascriptjsonreactjs

解决方案


发生这种情况是因为在组件的初始渲染之后componentDidMount运行。您可以在此处检查组件的生命周期,其中声明:

componentDidMount() 方法在组件输出被渲染到 DOM 之后运行。

在 render 方法中,您应该检查这是否为 null,与异步 (AJAX) Web 调用一样,无法保证您可以在初始渲染发生之前检索数据,即使您在渲染发生之前调用 AJAX。


推荐阅读