gpt4 book ai didi

javascript - 访问状态中的对象属性时返回null?

转载 作者:行者123 更新时间:2023-12-04 09:53:28 26 4
gpt4 key购买 nike

在我的 React.js 应用程序中,当我尝试访问存储在状态中的对象的属性时,我从 API 获取报价并将其存储在状态对象中。返回空值。

代码:

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

最佳答案

您必须注意您正在尝试异步获取数据,并且您在渲染后运行的 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>
);
}
}

关于javascript - 访问状态中的对象属性时返回null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61975117/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com