javascript - 动态获取 Youtube 视频

标签 javascript reactjs youtube youtube-data-api

我正在尝试使用 react.js 从您的管 channel 获取视频

我尝试使用 PHP CURL,得到了正确的响应。下面的代码显示空白页。 请帮忙。

import $ from 'jquery'; 
import React, { Component } from 'react';;

class iLotIndex extends Component {

constructor(props) {
    super(props);

    this.state = {video: []};
  }

VideoList() {
    return $.getJSON('https://www.googleapis.com/youtube/v3/search?key=AIzaxxxxxxxxxxxxxxxxxxxxx&channelId=UCexxxxxxxxxxxxxxxx&part=snippet,id&order=date&maxResults=20')
      .then((data) => {
        this.setState({ video : data.results });
      });
  }


  render() {
    this.VideoList().then(function(res){
      this.state = {video: res};
    });
    return (
      <div id="layout-content" className="layout-content-wrapper">
        <div className="panel-list">
          {this.state.video.map((item, i) =>{
            return(
              <h1>{item.items}</h1>

            )
          })}
        </div>
      </div>
    )
  }
}

最佳答案

this.VideoList() 调用移至 componentDidMount() 而不是 render():

constructor(props) {
  super(props);

  this.state = {video: []};
  this.VideoList = this.VideoList.bind(this);
}

VideoList() {
  fetch('https://www.googleapis.com/youtube/v3/search?key=AIzaxxxxxxxxxxxxxxxxxxxxx&channelId=UCexxxxxxxxxxxxxxxx&part=snippet,id&order=date&maxResults=20')
    .then(resp => resp.json())
    .then((resp) => {
      console.log(resp);
      //this.setState({video: resp.results});
      this.setState({video: resp.items});
      console.log(this.state.video);
    });


  //$.getJSON('https://www.googleapis.com/youtube/v3/search?key=AIzaxxxxxxxxxxxxxxxxxxxxx&channelId=UCexxxxxxxxxxxxxxxx&part=snippet,id&order=date&maxResults=20')
    //.then((data) => {
      //this.setState({ video : data.results });
    //});
}

componentDidMount() {
  this.VideoList();
}

render() {

  return (
    <div id="layout-content" className="layout-content-wrapper">
      <div className="panel-list">
        {this.state.video.map((item, i) =>{
          console.log(item);
          return(
            <h1>{item.items}</h1>

          )
        })}
      </div>
    </div>
  )
}

如果它还不能正常工作,请在这里发布一些错误,谢谢!

关于javascript - 动态获取 Youtube 视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43936728/

相关文章:

regex - YouTube安全搜索

youtube - GTMOAuth2Authentication 不工作

iPad 上的 Javascript 文件未刷新

javascript - Cordova 地理定位不准确

javascript - 在页面加载时分页显示最后一页上的所有表格行

node.js - 无法从 MERN 应用程序的后端在浏览器中接收/设置 cookie,后端托管在 heroku 上,前端托管在 netlify 上

reactjs - 如何在React Router 4中实现动态路由?

javascript - jquery ajax 到 php 脚本不保存数据

node.js - 有关如何为聊天应用程序设计良好架构的建议?

java - youtube-mp3 头文件?