1

The Twitch API displays a maximum of 60 records and a _next cursor for pagination. I can't find a way to map through all the results using the cursor in React using the map function.

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

How would I map through using the _next cursor with this mapping technique? Or is there a different way I could achieve it?

Below is the JSON response..

enter image description here

4

2 回答 2

2

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

例子 -

const api = 'https://api.twitch.tv/v5/videos/<CLIENT_ID>?after=<NEXT_CURSOR>
于 2019-02-20T16:57:48.213 回答
1

我的建议是递归调用 getComments 函数,如下所示,如果您想要一次获得所有结果或使用 loadmore 按钮并根据按钮单击将 _next 标记设置为状态。

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

    });
  }

于 2019-02-20T17:17:00.830 回答