【问题标题】:Returning null when accessing object properties in state?访问状态中的对象属性时返回null?
【发布时间】:2020-05-23 16:23:05
【问题描述】:

在我的 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

当我尝试console.log(this.state.quote) 时,它会打印出这个输出,很好。

当我尝试console.log(this.state.quote.quoteText) 时,它会返回can not read property

output showing can not find property

【问题讨论】:

    标签: javascript reactjs object react-lifecycle


    【解决方案1】:

    您必须注意您正在尝试异步获取数据,并且您在渲染后运行的 componentDidMount 中获取数据,因此将有一个初始渲染周期,您将无法获得可用的数据,this.state.quote 将为空

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

    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>
        );
      }
    }
    

    【讨论】:

    • 谢谢你,Shubham,你真的节省了我的时间并且理解了异步。
    • 很高兴能帮上忙 :-)
    【解决方案2】:

    当您访问 quoteText 而不检查对象中的键是否存在时,它会引发错误 -

    render(){
      if(this.state.quote && this.state.quote.hasOwnProperty('quoteText')){ 
        console.log(this.state.quote.quoteText);
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      相关资源
      最近更新 更多