首页 > 解决方案 > 使用 REACT.JS 从 JSON 文件中的获取请求中获取未定义的值

问题描述

我来自 Vue 环境我对此有点困惑,我读了一些与此类似的其他问题,但我无法使其工作,

为什么我不能回显从获取请求中获取的嵌套对象的值?

console.log之后setState得到了值,但在渲染中是未定义的,

import React, { Component } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends Component {
  constructor() {
    super();
    this.state = {
      isLoading: true,
      articles: {}
    };
  }

  componentDidMount() {
    this.setState({ loading: true });
    fetch("./articles.json")
      .then(response => response.json())
      .then(result => {
        this.setState({
          isLoading: false,
          article: result.blog.article
        });
        console.log(
          "componentDidMount__this.state.article=",
          this.state.article.link.title
        ); //this gets the value
      })
      .catch(error => {
        console.error(error);
      });
  }

  render() {
    //let articleTitle;
    // this gets error ----> console.log(this.state.article.link.title);
    // because .link is undefined

    // console.log(this.state.article);
    // if (this.state.article !== "undefined") {
    //   console.log("wait what?..");
    // if I changed the state in fetch why this stil
    //   articleTitle = this.state.article.link.title;
    // } else {
    //   articleTitle = "";
    // }

    // I assign "this.state.article.link.title" to a variable so I can avoid the error,
    //
    return (
      <div className="App">
        {/*<h1>{articleTitle}</h1> */}
        <h1>{this.state.article.link.title}</h1>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

文章.json

{
  "blog": {
    "article": {
      "id": 1,
      "title": " 1 lorem ipsum",
      "description": "lorem ipsum",
      "image": {
        "desktop": "https://via.placeholder.com/900x500?text=desktop",
        "tablet": "https://via.placeholder.com/600x400?text=tablet",
        "mobile": "https://via.placeholder.com/320x320?text=mobile"
      },
      "link": {
        "title": "lorem link",
        "url": "#"
      },
      "author": {
        "avatar": "https://via.placeholder.com/125x125?text=125x125",
        "name": "lorem ipsum"
      }
    }
  }
}

https://codesandbox.io/s/wo65w21kl5

标签: reactjs

解决方案


似乎this.state.article.link.titlethis.state.article === undefined.

解决方案是以更安全的方式检索this.state.article.link.title

这通常通过利用短路评估来实现。我还在下面的示例中使用了解构赋值默认参数

还建议分配默认值this.state,尤其是在处理不确定数据时。

// Default `this.state`.
this.state = {
  article: {link: {title: ''}},
  articles: {},
  isLoading: true,
}

// Safe retrieval of `title`.
const {article = {}} = this.state
const {link = {}} = article.link
const title = link.title || ''

推荐阅读