【问题标题】:React Native How to get multiple APIs at the same time?React Native 如何同时获取多个 API?
【发布时间】:2021-02-21 16:15:29
【问题描述】:

对于我的项目,我必须在我的项目中获取多个 API,这些 API 与其他 API 相关联,即它们具有相同的数据...

这是我的代码


export default class App extends React.Component {

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    Promise.all([
      getData(),
      getData('?page=2'),
    ])
      .then(([dataSource1, dataSource2]) => {
        this.setState({
          isLoading: false,
          isLoading2: false,
          dataSource1,
          dataSource2,
        });
      })
      .catch((error) => {
        // handle errors
      });
  }

  render() {
    const getData = (subpath = '') => fetch(`https://api.rawg.io/api/games${subpath}`)
      .then(res => res.json())
      .then(result => result.results);
    console.log(getData)
        

  }

我尝试使用 axios 但没有成功...

当我删除评论时,它只显示第二次提取...

【问题讨论】:

  • 您能否详细说明您的意思,获取多个 api 的?
  • 请提及 API 是如何相互链接的。提供的示例几乎没有解释任何内容。
  • link是urllink的延续,即2个api具有相同的json结构和相同的数据名称。否则,API 会太大

标签: javascript reactjs react-native get fetch


【解决方案1】:

您需要对每个 API 进行两次单独的 fetch 调用。要等待两者都完成,请使用Promise.all

const getData = (subpath = '') => fetch(`https://api.rawg.io/api/games${subpath}`)
    .then(res => res.json())
    .then(result => result.results);
componentDidMount() {
    Promise.all([
        getData(),
        getData('?page=2'),
    ])
        .then(([dataSource1, dataSource2]) => {
            this.setState({
                isLoading: false,
                isLoading2: false,
                dataSource1,
                dataSource2,
            });
        })
        .catch((error) => {
            // handle errors
        });
}

【讨论】:

  • 我在顶部编辑了我的代码,获取了您的代码,它给了我一条错误消息,getData is not defined。此消息来自下方的Promise.all componentDidMount () 。对不起,如果这个问题有点傻,这是我第一次使用 react native。
  • 听起来你忘了定义我在答案代码中定义的getData函数。
  • 你没有来创建一个getData 函数——你可以写出单独的fetch 调用——但那会很湿。最好尽可能编写DRY 代码。
  • 不,把它放在Promise.all 调用可以看到的地方——在它的外部范围内的某个地方,在componentDidMount 中,或者在与类定义相同的级别,或者在其他地方
  • 谢谢!在我的渲染中,我在 console.log() 中调用 getData。在里面,我有两个承诺:[[PromiseState]][[PromiseResult]],我想访问[[PromiseResult]] 来获取数组但我不能......因为双数组?
猜你喜欢
  • 2016-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-22
  • 1970-01-01
  • 2019-02-08
  • 1970-01-01
  • 2021-12-10
相关资源
最近更新 更多