Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/react-native/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Api 使用React Native Fetch的对象响应时未处理的承诺拒绝_Api_React Native_Promise_Fetch - Fatal编程技术网

Api 使用React Native Fetch的对象响应时未处理的承诺拒绝

Api 使用React Native Fetch的对象响应时未处理的承诺拒绝,api,react-native,promise,fetch,Api,React Native,Promise,Fetch,我目前正在使用他们的 我想展示当天的头条新闻。因此,首先我获得当天最热门帖子的id,然后使用这些id获取故事 但是当我运行此命令时,承诺会被拒绝,并且ids.map未定义 我怎样才能解决这个问题 FeedScreen.js import { getTopStoriesID, getStoriesByID } from '../../hacknews-api'; class FeedScreen extends Component { constructor(props) { sup

我目前正在使用他们的

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

但是当我运行此命令时,承诺会被拒绝,并且
ids.map未定义

我怎样才能解决这个问题

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;
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;
}
可以在数组而不是对象上使用

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
  }
}

如果您的
storiesID
是一个ID的
数组,那么您应该只传递数组,而不传递
const stories=await getStoriesByID(storiesID[10])中的任何索引。请尝试使用
const stories=wait getStoriesByID(storiesID)对于异步派生的数据,始终缓存承诺,而不是数据本身。