使用react js渲染youtube视频

时间:2018-08-04 19:27:34

标签: javascript reactjs google-api axios youtube-data-api

我的目标是将查询提供给youtube搜索,并在我的简单react js应用程序中呈现检索到的视频。在npm start之后,对于这个react组件,在localhost中什么也没有出现。在控制台中,我一直持续出现此错误,我使用axios从API提取数据:

Yutube.js:23 Error: Request failed with status code 400
    at createError (createError.js:16)
    at settle (settle.js:18)
    at XMLHttpRequest.handleLoad (xhr.js:77)

这是我的YoutubeRitriver react JS组件:

import React, { Component } from 'react';
import axios from 'axios';

export default class YouTube extends Component {
constructor(props) {
    super(props);

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

componentWillMount() {
    setInterval(() => {
        this.VideoList();
    }, 2000)
}
VideoList() {
    axios.get('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=UUbW18JZRgko_mOGm5er8Yzg&key={MY DATA GOOGLE KEY')
        .then((response) => {
            this.setState({video: response.headers});
        })
        .catch(function (error) {
            console.log(error);
        });
}
render() {
    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>
    )
}
}

2 个答案:

答案 0 :(得分:0)

我认为您必须将VideoList方法作为异步操作的中间件来处理,因为您在ComponentWillMount中执行了它,因此您的间隔计时器将永远无法到达,因为建议停止使用ComponentWillMount,您可以在ComponentDidMount中尝试异步操作,但是我们将寻求更好的答案:-) ..

答案 1 :(得分:0)

首先,在返回400 http状态时,检查提供的URL以获取。

  

400错误请求
  服务器无法或将不处理请求   认为是客户错误的内容(例如格式错误)   请求语法,无效的请求消息框架或欺骗性请求   路由)。

来源:httpstatuses

您的axios调用应如下所示(具体检查key=部分) axios.get('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=UUbW18JZRgko_mOGm5er8Yzg&key=[your-api-key]')

用您的API密钥替换[your-api-key]

您可以使用Postman来检查您的呼叫并确保其正常工作。它还可以洞悉返回的数据。据我所知,您可以使用以下this.setState({video: response.headers});

来设置状态

当我检查提取结果时。我收到具有以下结构的json对象。

{
  "kind": "youtube#playlistItemListResponse",
  "etag": "\"XI7nbFXulYBIpL0ayR_gDh3eu1k/ipQV3_cO6U60ZQAQFbmLuvvwHsI\"",
  "nextPageToken": "CAUQAA",
  "pageInfo": {
      "totalResults": 171,
      "resultsPerPage": 5
  },
  "items": [
      {
          "kind": "youtube#playlistItem",
          "etag": "\"XI7nbFXulYBIpL0ayR_gDh3eu1k/qKI5Yg1Vl2i2-2N6r0fbQoupdS0\"",
          "id": "VVViVzE4SlpSZ2tvX21PR201ZXI4WXpnLlRId1hfbEUtbElJ",
          "snippet": {
              "publishedAt": "2018-01-30T09:35:59.000Z",
              "channelId": "UCbW18JZRgko_mOGm5er8Yzg",
              "title": "One Direction - One Way or Another (Teenage Kicks) (Live at the BRIT Awards 2013)",
              "description": "One Direction - One Way Or Another (Teenage Kicks) live from The BRIT Awards 2013.\n\nStream more music from One Direction here: http://smarturl.it/OneDSpotify \n\nMore from One Direction:\nDrag Me Down: https://youtu.be/Jwgf3wmiA04 \nPerfect: https://youtu.be/Ho32Oh6b4jc \nHistory: https://youtu.be/yjmp8CoZBIo \nNight Changes: https://youtu.be/syFZfO_wfMQ \nSteal My Girl: https://youtu.be/UpsKGvPjAgw \nKiss You: https://www.youtube.com/watch?v=T4cdfRohhcg  \nYou & I: https://www.youtube.com/watch?v=_kqQDCxRCzM   \nStory of My Life: https://www.youtube.com/watch?v=W-TE_Ys4iwM  \n\nFollow One Direction:\nFacebook https://www.facebook.com/onedirectionmusic/   \nTwitter https://twitter.com/onedirection  \nInstagram https://www.instagram.com/onedirection/   \n\nMore great videos here http://smarturl.it/1DVevoX  \n\nSubscribe to One Direction on YouTube: http://smarturl.it/1DYT\n\nhttp://vevo.ly/YkR6Yy",
              "thumbnails": {},
              "channelTitle": "OneDirectionVEVO",
              "playlistId": "UUbW18JZRgko_mOGm5er8Yzg",
              "position": 0,
              "resourceId": {
                  "kind": "youtube#video",
                  "videoId": "THwX_lE-lII"
              }
          }
      }, {
        // next item
      }, {
        // another item
      }
    ]
}

确保分配项目以正确陈述状态。可能看起来像这样。
this.setState({video: response.data.items});

然后,当在其上进行映射时,请使用以下内容显示标题。 this.state.video.map((item, i) => <h1 key={i}>{item.snippet.title}<h1>)