【发布时间】: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 个小时来解决这个问题。我在网上没有得到任何解决方案
当我尝试console.log(this.state.quote) 时,它会打印出这个输出,很好。
当我尝试console.log(this.state.quote.quoteText) 时,它会返回can not read property
【问题讨论】:
标签: javascript reactjs object react-lifecycle