import React, { Component } from "react";
import Header from "components/Header/Header.jsx";
import Footer from "components/Footer/Footer.jsx";
class Coach extends Component {
constructor(props){
super(props)
this.state = {
title : '',
duration : '',
url : '',
video_id : ''
}
}
youtube_api_key = "AIzaSyD8IX7eL0hyIDos4L9tqZ1RyVpqBL6tNuw";
getVideoTitle(video_id) {
let title_url = `https://www.googleapis.com/youtube/v3/videos?id=${video_id}&key=${this.youtube_api_key}&fields=items(snippet(title))&part=snippet`
fetch(title_url)
.then(response => response.json())
.then(users => {
return users['items'][0]['snippet']['title']
})
}
getVideoDuration(video_id) {
let duration_url = `https://www.googleapis.com/youtube/v3/videos?id=${video_id}&part=contentDetails&key=${this.youtube_api_key}`;
fetch(duration_url)
.then(response => response.json())
.then(users => {
return users['items'][0]['contentDetails']['duration']
})
}
HandleUrl = (event) => {
this.setState({url:event.target.value})
}
SubmitUrl = () => {
let url = this.state.url;
let video_id = ''
if (url.split('?').length > 1){
video_id = url.split("?")[1].split("=")[1];
} else {
video_id = url;
}
let title = this.getVideoTitle(video_id)
let duration = this.getVideoDuration(video_id)
let id = localStorage.getItem("id")
console.log(this.title, this.duration, id)
fetch('http://127.0.0.1:8000/video/', {
method: 'post',
headers:{'Content-Type': 'application/json'},
body: JSON.stringify({
title : this.state.title,
duration : this.state.duration,
id : id,
url : video_id
})
})
.then(response => response.json())
.then(res => {
console.log(res)
})
}
render() {
return (
<div>
<Header />
<section>
<br/>
<div className="block no-padding">
<div className="container">
<div className="row">
<div class="col-lg-12 column">
<div class="contact-form">
<h3>Upload Videos</h3>
<div style={{ float: 'left', width: '100%', display: 'block' }}>
<div class="row">
<div class="col-lg-10">
<div class="pf-field">
<input type="text" placeholder="Video Url" onChange={ this.HandleUrl } />
</div>
</div>
<div class="col-lg-2">
<button type="button" onClick={this.SubmitUrl }>Submit</button>
</div>
</div>
</div>
</div>
</div>
</div>
<br/>
<div>
<table class="table table-hover table-borderless">
<thead style={{ background:'#fb236a',borderRadius:'5px', color:'#fff' }}>
<tr>
<th style={{ border:'none' }}>Firstname</th>
<th style={{ border:'none' }}>Lastname</th>
<th style={{ border:'none' }}>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td style={{ border:'none' }}>John</td>
<td style={{ border:'none' }}>Doe</td>
<td style={{ border:'none' }}>john@example.com</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</section>
<Footer />
</div>
)
}
}
export default Coach;
在这里,我通过传递 video_id 来调用 SubmitUrl()中的 getVideoTitle()和 getVideoDuration()函数但我收到的数据为空。
,但在控制台内部显示相同的功能。 我也通过将数据保持在内部状态来进行尝试。
当我将状态添加到状态后再从状态中重现数据时,仍然显示为空。
请看一下我的代码。