Reactjs 未捕获(承诺中)类型错误:无法读取属性';图像';未定义的(…;)
我正在学习如何应对,不知道如何解决我的问题。我正在从Reddit导入数据。我能够从JSON数据中输出标题和id,但是当我尝试对图像url执行相同操作时,我得到了Uncaught(承诺)TypeError:无法读取未定义(…)的属性“images” 以下是我的代码(变量filteredPosts是发生错误的地方),下面我将包括JSON文件的一部分:Reactjs 未捕获(承诺中)类型错误:无法读取属性';图像';未定义的(…;),reactjs,Reactjs,我正在学习如何应对,不知道如何解决我的问题。我正在从Reddit导入数据。我能够从JSON数据中输出标题和id,但是当我尝试对图像url执行相同操作时,我得到了Uncaught(承诺)TypeError:无法读取未定义(…)的属性“images” 以下是我的代码(变量filteredPosts是发生错误的地方),下面我将包括JSON文件的一部分: import React from "react"; import Projects from "./Projects"; import axios
import React from "react";
import Projects from "./Projects";
import axios from 'axios';
export default class MainContainer extends React.Component{
constructor(props){
super(props);
this.state = {
posts: []
}
}
componentDidMount(){
axios.get('https://www.reddit.com/r/reactjs.json')
.then(res => {
const posts = res.data.data.children.map(obj => obj.data);
this.setState({posts});
})
}
render() {
var filteredPosts = this.state.posts.map(post => <Projects key={post.id} title={post.title} imgSrc={post.preview.images[0].source.url}></Projects>);
return (
<div>
<div className="container">
<div className="row">
<div className="col-lg-12">
<h1 className="page-header">My Project
<small> made with React.js</small>
</h1>
</div>
</div>
<div className="row">
{filteredPosts}
</div>
<hr/>
<div className="row text-center">
<div className="col-lg-12">
<ul className="pagination">
<li>
<a href="#">«</a>
</li>
<li className="active">
<a href="#">1</a>
</li>
<li>
<a href="#">2</a>
</li>
<li>
<a href="#">3</a>
</li>
<li>
<a href="#">4</a>
</li>
<li>
<a href="#">5</a>
</li>
<li>
<a href="#">»</a>
</li>
</ul>
</div>
</div>
</div>
</div>
);
}
}
问题是你假设每一篇文章都有一个预览属性。我自己做了ajax调用,在每篇文章上做了控制台日志,发现至少有6篇文章没有preview属性 你需要更具防御性,有一个默认的图像或只是空白背景。你可以这样做:
imgSrc={post.preview?post.preview.images[0]。source.url:defaultImg}
这是假设您有一个defaultImg,而不仅仅是在其中返回一个空字符串
这里还有一个假设,即如果preview属性存在,那么image属性也将与source.url一起存在。在检查子属性之前,通过检查属性是否存在来进行更多的防御性编程
另外,作为最后一个选项,如果您只想发布带有预览的文章,您可以执行一个简单的筛选:
this.state.posts.filter((post) => post.preview) // returns only posts with preview property
this.state.posts.filter((post) => post.preview) // returns only posts with preview property