首页 > 解决方案 > 使用 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>
    );
  }
}

标签: javascriptreactjs

解决方案


正如@Bravo 在评论中所说,您的回传undefined.thread不存在)。传回threads.data.children || []默认为数组,以防止出现意外结果时出错:

  async componentDidMount() {
    let threads = await fetchCatThreads();
    this.setState({ threads: threads.data.children || [], loading: false });
  }

希望这可以帮助,


推荐阅读