gpt4 book ai didi

javascript - "TypeError: Cannot read property ' 名称 ' of undefined"错误

转载 作者:行者123 更新时间:2023-11-28 17:14:29 25 4
gpt4 key购买 nike

代码给了我这个“TypeError:无法读取未定义的属性'名称'”错误,尽管当我console.log时它给了我对象

import React from "react";

class Random extends React.Component {
constructor(props) {
super(props);
this.state = {
breweries: []
};
}

componentDidMount() {
fetch("https://api.openbrewerydb.org/breweries")
.then(response => response.json())
.then((data) => {
this.setState({
breweries: data,
})
})
}

render() {
const brewery = this.state.breweries[Math.floor(Math.random()*this.state.breweries.length)];
return(
<div>{brewery.name}</div>
)
}
}

export default Random;

最佳答案

直到异步请求完成,

this.state.breweries[Math.floor(Math.random()*this.state.breweries.length)] 

实际上会返回未定义,因为

Math.floor(Math.random()*this.state.breweries.length)

将返回0,并且由于this.state.breweries是一个空数组,因此它将返回undefined

([][0] -> 未定义)。

<小时/>

您必须确保 brewery 尚未定义的可能性,例如:

<div>{brewery && brewery.name}</div>

关于javascript - "TypeError: Cannot read property ' 名称 ' of undefined"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53803999/

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