首页 > 解决方案 > 使用 react js 渲染 youtube 视频

问题描述

我的目标是将查询提供给 youtube 搜索并在我的简单反应 js 应用程序中呈现检索视频。我在npm start这个反应组件之后,本地主机中什么都没有出现。在控制台中我不断地遇到这个错误,我使用 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>
    )
}
}

标签: javascriptreactjsgoogle-apiaxiosyoutube-data-api

解决方案


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


推荐阅读