首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用cursor - React映射Twitch API的所有结果

如何使用cursor - React映射Twitch API的所有结果
EN

Stack Overflow用户
提问于 2019-02-21 00:44:57
回答 2查看 244关注 0票数 1

Twitch API最多显示60条记录和一个用于分页的_next光标。在使用map函数的React中,我找不到一种使用光标映射所有结果的方法。

代码语言:javascript
复制
  componentDidMount() {
    this.getComments();
  }

  getComments(){
    const api = 'https://api.twitch.tv/v5/videos/'+ this.state.value +'/comments?client_id='+ this.state.cid;
    fetch(api, {
      method: 'get',
      headers: {"Client-ID": this.state.cid}
    })
    .then((response) => response.text())
      .then((responseText) => {
        this.setState({hits : (JSON.parse(responseText)), api: api})
     });
   }



   render(){

    const { hits } = this.state;
    console.log({hits});

    return (
      <div>
         <ul id="results">
           { hits && hits.comments && hits.comments.length !== 0 ?
                 hits.comments.map(hit =>
                   <li key={hit._id}>
                     <span>[{this.convertSeconds(hit.content_offset_seconds)}] - {hit.message.body}</span>
                   </li>
                 )
              :
                 <div>No Comments Found</div>
           }
         </ul>
     </div>
    );
  }

如何通过这种映射技术使用_next游标进行映射?或者有没有不同的方法可以实现它?

下面是JSON响应。

EN

回答 2

Stack Overflow用户

发布于 2019-02-21 00:57:48

要获得分页响应,需要再次调用Twitch API,并将after查询参数或before查询参数中的游标传递给twitch调用。

示例:

代码语言:javascript
复制
const api = 'https://api.twitch.tv/v5/videos/<CLIENT_ID>?after=<NEXT_CURSOR>
票数 2
EN

Stack Overflow用户

发布于 2019-02-21 01:17:01

我的建议是,如果你想一次得到所有结果,就像下面这样递归调用getComments函数,或者使用loadmore按钮,并根据按钮点击将_next标记设置为状态。

代码语言:javascript
复制
let result = []
getComments(){
   const api = 'https://api.twitch.tv/v5/videos/'+ this.state.value +'/comments?client_id='+ this.state.cid;
   fetch(api, {
     method: 'get',
     headers: {"Client-ID": this.state.cid}
   })
   .then((response) => response.text())
     .then((responseText) => {
       // add response untill you get all results
       if(responseText){
          //store array of response objects
          this.setState({
           hits : [...this.state.hits, ...responseText],
           cid : "YOUR NEW CURSOR ID FROM RESPONSE"})
           getComments()
       } else {
          //exist the recursion
          return ;
       }

    });
  }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54791400

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档