gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'length' of undefined in react

转载 作者:行者123 更新时间:2023-12-01 00:42:31 25 4
gpt4 key购买 nike

我正在构建一个 React 网站,它将从 newsapi 获取数据并显示在卡片上。在检查是否有一个长度之后,它将显示或显示替代响应,我收到此错误。“类型错误:无法读取未定义的属性‘长度’”

这是我编码的内容:

import React, { Component } from 'react';


class Cards extends Component {
constructor () {
super();
this.state = {
post: [
{
author:"",
discription:"",
publishedAt:"",
title:"",
urlToImage:""
}
]
};
}

componentDidMount() {
fetch('https://newsapi.org/v2/top-headlines?' +
'country=us&' +
'apiKey=GIVEN API KEY')
.then(response => response.json())
.then(response => this.setState({post :response}));
}
render() {
const { post } = this.state;
const postlist = post.length ? (
post.map(post => {
return (
<div>
<div class="container card mb-3">
<div class="row no-gutters">
<div class="col-md-4">
<img src={post.urlToImage} class="card-img" alt="..."/>
</div>
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title">{post.title}</h5>
<p class="card-text">{post.description}</p>
<div class="row">
<p class="card-text col-6"><small class="text-muted">{post.author}</small></p>
<p class="card-text col-6"><small class="text-muted">{post.publishedAt}</small></p>
</div>
</div>
</div>
</div>
</div>
</div>
);
})
)
: (
<div class="center">No post yet!</div>
);


return (
<div class="container">
<h2>Latest News</h2>
{postlist}
</div>
);
}
}

export default Cards;

最佳答案

解构 this.state 时出现错误。 const { post } = this.state.post; 应该是 const { post } = this.state;

编辑来自 https://newsapi.org看起来响应的结构将是 {status: ...,totalArticles: ...,articles: [...]}。所以你的 componentDidMount 应该是:

componentDidMount() {
fetch('https://newsapi.org/v2/top-headlines?' +
'country=us&' +
'apiKey=GIVEN API KEY')
.then(response => response.json())
.then(response => this.setState({post :response.articles}));
}

关于javascript - 类型错误 : Cannot read property 'length' of undefined in react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57614233/

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