从API提取YouTube视频能够通过按钮Onclick显示,需要在页面上显示,而不是通过按钮单击直接在我的页面上显示

问题描述

无法直接在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

解决方法

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...