【问题标题】:Fetching YouTube videos from API able to display through button Onclick, need to display on page not through button click want directly on my page从 API 获取 YouTube 视频能够通过按钮 Onclick 显示,需要在页面上显示而不是通过按钮点击直接在我的页面上
【发布时间】:2021-02-24 05:12:21
【问题描述】:

无法在我的网页上直接在 reactjs 中显示 youtube 视频,只能通过 Onclick 按钮来实现,但我不需要单击任何按钮来在我的页面上获取视频,我希望视频直接显示在我的网页获取数据后,尝试更改代码但无法找到解决方案,我是编码新手,需要对代码进行任何更改以使视频在网页上显示而无需点击。

const finalURL = `https://youtube.googleapis.com/youtube/v3/search?part=snippet&channelId=${ChannelID}&maxResults=${result}&key=${API}`

class Youtube extends Component {
    
    constructor(props) {
        super(props)
    
        this.state = {
            resultyt: []
        };

        this.Clicked= this.Clicked.bind(this);
    }

    Clicked() {
    fetch (finalURL)
    .then((response) => response.json())
    .then((responseJson) => {
const resultyt = responseJson.items.map(obj => "https://www.youtube.com/embed/"+obj.id.videoId);
this.setState({resultyt});

    })
.catch((error) => {
    console.error(error);
})



    }
    
    render() {

        return (

<div>
    <button onClick={this.Clicked}>
        My Channel Videos
        </button>
    {
            this.state.resultyt.map((link,i) => {
                var frame = <div key={i} className='Guru'><iframe width="200" height="100" src={link} frameBorder="0" allowFullScreen></iframe> </div>
        return frame;
            })
        }
    
    
{this.frame}
    
    
</div>


            )
        }
    }
    
    



export default Youtube

【问题讨论】:

  • 将 Clicked() 的主体放在 componentDidMount 中,它应该可以工作
  • 我想删除按钮,只需要从获取的数据中显示视频,而不是点击其他需要的功能。

标签: javascript reactjs fetch youtube-iframe-api jsonresult


【解决方案1】:

您应该使用componentDidMount。更多信息在这里:https://en.reactjs.org/docs/faq-ajax.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 2012-05-13
    相关资源
    最近更新 更多