【问题标题】:Reactjs - How can I loop through an API that has been chained using axios?Reactjs - 如何循环使用 axios 链接的 API?
【发布时间】:2020-08-31 19:36:27
【问题描述】:

我正在尝试使用黑客新闻 API 构建一些东西,但我遇到了问题。将项目显示到屏幕上。我需要的项目首先需要调用另一个端点。我调用了这个端点并遍历它,以便我可以将数据从那个端点传递到我需要工作的项目端点,但我只显示一个项目。我怎样才能进一步做到这一点以一次获得大约 30 件物品?

state={
    hackernews: []
  }
  componentDidMount(){
    Axios.get('/newstories.json')
    .then(res => {
      for(let i = 0; i<res.data.length; i++){
        const newsID = res.data[i];
        return Axios.get(`/item/${newsID}.json`)
      }
    })
    .then(res=>{
      const news = res.data
      this.setState({hackernews: [...this.state.hackernews, news]})
      
    })
  }

hackernews api链接https://github.com/HackerNews/API

【问题讨论】:

    标签: javascript reactjs api axios


    【解决方案1】:

    您可以使用async/await 获取ID,然后正常使用.then

     async componentDidMount(){
       let res=await Axios.get('/newstories.json')
    
         for(let i = 0; i<res.data.length; i++){
            const newsID = res.data[i];
           Axios.get(`/item/${newsID}.json`)  
           .then(res1=>{
              const news = res1.data
              this.setState({hackernews: [...this.state.hackernews, news]})
          
             })
         }
    
    }
    

    【讨论】:

    • 非常感谢。但是,有一个问题。它出现在屏幕上但会引发错误。
    • 它继续循环遍历这些项目,直到它为我正在尝试做的事情抛出一个 null 错误。我已经使用 params 方法来限制它,但它仍然抛出它。我会在网上寻找更多信息。
    • 如果有很多细节你可以发布另一个问题
    猜你喜欢
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多