gpt4 book ai didi

javascript - React 然后返回无法读取未定义的属性

转载 作者:行者123 更新时间:2023-11-28 17:45:02 25 4
gpt4 key购买 nike

我正在开发使用 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;

最佳答案

Uncaught TypeError: Cannot read property 'then' of undefined

由于代码中 .then 的唯一实例遵循对 Youtube.search 的调用,因此 Youtube.search 大部分不会返回 Promise,这又意味着 YTSearch 不会返回 Promise。看起来它是一个回调 api,而不是一个 promise api,所以你需要自己将它包装在一个 promise 中:

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
};
}));
});
});
}
}

关于javascript - React 然后返回无法读取未定义的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46945199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com