当用户单击特定选项时,我正在使用react和routers显示来自一系列subreddit的线程。但是,我一直收到“无法读取未定义的属性'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 - 使用reddit json时 map 未定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58262143/