【问题标题】:Unhandled Promise Rejection while using object response from React Native Fetch使用来自 React Native Fetch 的对象响应时未处理的 Promise Rejection
【发布时间】:2018-08-11 07:47:17
【问题描述】:

我目前正在使用他们的Official API 在 React Native 中构建一个黑客新闻阅读客户端

我想展示当天的热门新闻。因此,我首先获取当天热门帖子的 ID,然后使用这些 ID 获取故事。

但是当我运行这个时,promise 会被ids.map is undefined 拒绝。

我该如何解决这个问题?

FeedScreen.js

import { getTopStoriesID, getStoriesByID } from '../../hacknews-api';

class FeedScreen extends Component {
  constructor(props) {
    super(props);

    this.state = {
      loaded: false,
      stories: [],
    };
  }

  async componentDidMount() {
    const storiesID = await getTopStoriesID();
    const stories = await getStoriesByID(storiesID[10]);

    this.setState({ stories });
  }

  render() {
    return <Text>{this.state.stories}</Text>;
  }
}

export default FeedScreen;

hacknews-api.js

const BASE_URL = 'https://hacker-news.firebaseio.com/v0';

export const getTopStoriesID = async () => {
  const res = await fetch(BASE_URL + '/topstories.json');
  const storiesID = await res.json();

  return storiesID;
};

export const getStoriesByID = async (ids) => {
  const res = await Promise.all(ids.map(async (id) => {
    const res = await fetch(BASE_URL + `/item/{id}.json`)
    const story = await res.json();

    return story;
  }));

  const stories = await res.json();
  return stories;
}

【问题讨论】:

  • 如果您的storiesIDarray of ids,那么您应该只传递数组而不是const stories = await getStoriesByID(storiesID[10]); 中的任何索引。请尝试const stories = await getStoriesByID(storiesID);
  • 对于异步派生的数据,总是缓存 Promise,而不是数据本身。

标签: api react-native promise fetch


【解决方案1】:

您可以在数组而不是对象上使用Array.prototype.map()

map() 方法创建一个带有调用结果的新数组 在调用数组中的每个元素上提供函数。

示例

export const getStoriesByID = async (ids) => {
  // check if the argument is defined and its an Array
  if(ids && ids.constructor === Array) {
    // do something with array of ids, for example do a map()
  } else {
    // do something otherwise
  }
}

【讨论】:

    猜你喜欢
    • 2018-08-06
    • 2018-04-12
    • 1970-01-01
    • 2017-01-25
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 2021-06-05
    相关资源
    最近更新 更多