gpt4 book ai didi

javascript - React 嵌套对象给出错误

转载 作者:行者123 更新时间:2023-12-01 03:04:08 25 4
gpt4 key购买 nike

我有一个可以工作的组件,只要它没有嵌套,就会从 State 返回数据。但是,如果我需要在对象中更深入地挖掘,则会收到错误:“TypeError:无法读取未定义的属性“名称””。

我确信它有一个值(检查了 Inspector 并且该变量确实有一个值,这就是我知道要在代码中放入什么内容的方式)。为什么它适用于较高的值,但不适用于较低的值?

class Concert extends Component {

constructor(props) {
super(props);

this.state = ({
concert:''
})
}
componentDidMount(){
var concertid = `${REQ_URL}/${this.props.match.params.concertid}`;
fetch(concertid, {
method: 'GET'
})
.then(response => response.json())
.then(json => {
this.setState({
concert:json
})
})


}
render() {
return (
<div>
<Header />
<div className="concert">
<div className="venue">

//THIS IS THE PART THAT RETURNS ERROR
//this.state.concert.id returns a correct value
//POSITIVE this.state.concert.artist.name DOES CONTAIN VALUE

Venue: {this.state.concert.artist.name}
</div>

</div>
</div>
)
}

}

最佳答案

组件第一次渲染时,this.state.concert的值是 '' (您在构造函数中设置该值)所以如果您尝试访问 this.state.concert.artist.name您实际上正在尝试访问 undefined.name - 这是你的错误。

this.state.concert的值仅在组件加载后才发生更改 - 在 success 之后您的回调fetch调用完成,只有这样该值才可用。

您可以做的是在访问值之前检查是否有值:

{this.state.concert && this.state.concert.artist &&
<div>Venue: {this.state.concert.artist.name}</div>
}

关于javascript - React 嵌套对象给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46309882/

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