我正在开发使用Youtube返回视频列表的应用。为了查询youtube API,我使用youtube-api-search
npm模块。应用程序从搜索栏获取术语,将其传递给应用程序,然后调用激活搜索的方法。在Youtube.js
文件中,console.log会按预期返回5个视频的数组,但是当我链接到app.js时,我收到了一个错误 - 无法读取未定义的属性。
//App.js
import React, { Component } from 'react';
import './App.css';
import SearchBar from '../Searchbar/Searchbar';
import VideoList from '../VideoList/VideoList';
import Youtube from '../../utils/Youtube';
class App extends Component {
constructor(props) {
super(props);
this.state = {
videos: []
}
this.searchYoutube = this.searchYoutube.bind(this);
}
searchYoutube(term) {
Youtube.search(term)
.then(videos => {
// console.log("app videos", video);
this.setState({
videos: videos
});
});
}
render() {
return (
<div className="App">
<SearchBar onSearch={this.searchYoutube} />
<VideoList videos={this.state.videos}/>
</div>
);
}
}
export default App;
//Youtube.js
import YTSearch from 'youtube-api-search';
const API = 'xxxxx';
const Youtube = {
search(term) {
return YTSearch({ key: API, term: term }, (data) => {
return data.map(video => {
console.log('youtube title: ', video.snippet.title);
return {
title: video.snippet.title,
url: video.snippet.thumbnails.default.url,
description: video.snippet.description,
id: video.etag
}
});
});
}
}
export default Youtube;
//Searchbar.js
import React, { Component } from 'react';
import './Searchbar.css';
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = {
term: ''
}
this.inputSearch = this.inputSearch.bind(this);
this.handleSearch = this.handleSearch.bind(this);
}
inputSearch(e) {
this.setState({
term: e.target.value
});
}
handleSearch(e) {
this.props.onSearch(this.state.term);
e.preventDefault();
}
render() {
return (
<div className="row">
<input type="text" onChange={this.inputSearch} className="input_searchbar" id="inlineFormInput" placeholder="Enter search term" />
<button onClick={this.handleSearch} className="button_searchbar ">Submit</button>
</div>
)
}
}
export default SearchBar;
答案 0 :(得分:3)
未捕获的TypeError:无法读取未定义的属性“然后”
由于代码中唯一的.then实例跟随对Youtube.search的调用,因此Youtube.search最不会返回一个promise,这反过来意味着YTSearch没有返回一个promise。它看起来像是一个回调api,而不是一个promise api,所以你需要自己将它包装在一个承诺中:
const Youtube = {
search(term) {
return new Promise(resolve => {
YTSearch({ key: API, term: term }, (data) => {
resolve(data.map(video => {
return {
title: video.snippet.title,
url: video.snippet.thumbnails.default.url,
description: video.snippet.description,
id: video.etag
};
}));
});
});
}
}