javascript - 使用 reddit json 时映射未定义
问题描述
当用户单击特定选项时,我正在使用 react 和路由器显示来自一系列 subreddits 的线程。但是我不断收到“无法读取未定义的属性'map'”的错误,我不知道为什么。
import React from 'react';
import { fetchCatThreads } from './RedditApi';
import ThreadCard from './ThreadCard';
import Loading from './Loading';
export default class CatsPage extends React.Component {
constructor(props) {
super(props);
this.state = {
threads: [],
loading: true
};
}
async componentDidMount() {
let threads = await fetchCatThreads();
this.setState({ threads:threads.thread, loading: false });
}
render() {
return (
<div className="threads">
{this.state.loading ? <Loading /> : this.state.threads.map((thread) => {
return <ThreadCard thread={thread} />
})}
</div>
);
}
}
解决方案
正如@Bravo 在评论中所说,您的回传undefined
(.thread
不存在)。传回threads.data.children || []
默认为数组,以防止出现意外结果时出错:
async componentDidMount() {
let threads = await fetchCatThreads();
this.setState({ threads: threads.data.children || [], loading: false });
}
希望这可以帮助,
推荐阅读
- javascript - 使用 PDFBox 2.x 在 PDF 上放置一个按钮
- python - 如果不为空,则将参数传递给方法
- c# - C# ConcurrentDictionary 条件添加
- python - 加入两个 modin.pandas.DataFrame(s)
- python - 如何/我可以从 Python 中的 Twitter 帐户中检索文本数据
- numpy - 创建一个绿色通道比蓝色和红色更亮的蒙版?
- c++ - 编译错误“错误:预期的';' 在声明列表末尾”使用 C++ 中的 Catch 测试框架
- python-3.x - 如何识别文本编码问题是我的处理错误还是来自源 pdf
- reactjs - React Bootstrap Table - 识别一行
- php - 根据另一个数组从数组中删除行