【问题标题】:How to map all results from Twitch API using cursor - React如何使用光标映射来自 Twitch API 的所有结果 - React
【发布时间】:2019-07-14 10:35:48
【问题描述】:

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

  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 响应..

【问题讨论】:

  • 你能发布你的 JSON 响应吗?
  • 已添加...谢谢

标签: javascript reactjs api twitch twitch-api


【解决方案1】:

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

例子-

const api = 'https://api.twitch.tv/v5/videos/<CLIENT_ID>?after=<NEXT_CURSOR>

【讨论】:

  • 嗯,对了,我明白了。我将如何使用上面实现的地图功能来做到这一点?
  • @TylerWatts 将响应存储在状态中并相应地使用令牌。
【解决方案2】:

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

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

    });
  }

【讨论】:

  • 啊,对,这是个好方法。不过,我如何从该 cid 字段中的 responseText 获取 _next 值?我试过 cid: JSON.parse(responseText)._next 但我认为不对
  • 你在哪里挣扎……你在 responseText 中得到了什么数据?
  • 它返回一个多维数组,我在映射时遇到问题
猜你喜欢
  • 2020-10-28
  • 2019-07-14
  • 2015-12-13
  • 2021-11-09
  • 2018-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
相关资源
最近更新 更多