在状态下访问对象属性时返回null?

在我的React.js应用程序中,当试图访问存储在状态中的对象的属性时,我从API提取了一个报价并将其存储在状态对象中。返回null。

码:

import React, { Component } from "react";

export default class Quotes extends Component {
  constructor(props) {
    super(props);

    this.state = {
      quote: null,
    };
  }

  componentDidMount() {
    fetch("https://quote-garden.herokuapp.com/api/v2/quotes/random")
      .then((response) => response.json())
      .then((quote) => this.setState({ quote: quote.quote }))
      .catch((error) => console.log(error));
  }
  render() {
    console.log(this.state.quote.quoteText); //This is returning null
    console.log(this.state.quote); //This is working fine.
    return (
      <div>
        <p>// Author of Quote</p>
      </div>
    );
  }
}

我是React.js的新手,我花了大约2个小时来解决这个问题。我在网上没有任何解决方案

output showing quote object

When I try to console.log(this.state.quote) it prints out this output, well it is fine.

and when I try console.log(this.state.quote.quoteText) It will return can not read property

output showing can not find property

评论
太假
太假

You must note the you are trying to fetch data asynchronously and also you fetch data in componentDidMount which is run after render, so there will be an initial rendering cycle wherein you will not have the data available to you and this.state.quote will be null

处理此类情况的最佳方法是保持加载状态并仅在数据可用后进行所有处理

import React, { Component } from "react";

export default class Quotes extends Component {
  constructor(props) {
    super(props);

    this.state = {
      quote: null,
      isLoading: true,
    };
  }

  componentDidMount() {
    fetch("https://quote-garden.herokuapp.com/api/v2/quotes/random")
      .then((response) => response.json())
      .then((quote) => this.setState({ quote: quote.quote, isLoading: false }))
      .catch((error) => console.log(error));
  }
  render() {
    if(this.state.isLoading) {
     return <div>Loading...</div>
   }
    console.log(this.state.quote.quoteText); //This is returning proper value
    console.log(this.state.quote); 
    return (
      <div>
        <p>// Author of Quote</p>
      </div>
    );
  }
}
点赞
评论