【发布时间】:2018-04-09 05:27:37
【问题描述】:
我了解 Promise 的工作原理,并且过去曾使用 JQuery 来执行 Promise。我正在构建一个非常简单的应用程序,它使用 YouTube API 来显示视频。我遇到了砖墙,因为我遇到了需要使用 Promise 但不知道如何使用的情况。
在我的 index.js 文件中,我定义了一个 App 类,它的构造函数调用 API 以获取与默认搜索词“国家地理”匹配的视频列表。一旦这些结果回来(需要在这里使用一个承诺),我想调用 this.setSelectedVideo 来播放特定的视频。
// Node Modules
import React from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';
// Components
import SearchBar from './components/search_bar';
import VideoList from './components/video_list';
import VideoDetail from './components/video_detail';
const API_KEY_YOUTUBE = <MY_YOUTUBE_API_KEY>;
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
videos: [],
selectedVideo: null
};
// initialize videos: finish this up when you learn how to do redux promises
this.videoSearch('National Geographic');
this.setSelectedVideo(this.state.videos[0]);
}
videoSearch(term) {
// Make AJAX request to YouTube for a list of videos matching term.
YTSearch({ key: API_KEY_YOUTUBE, term: term }, videos => {
this.setState({ videos: videos });
});
}
setSelectedVideo(video) {
// Make AJAX request to YouTube for the specific video being played.
console.log(video);
}
render() {
return (
<div>
<div className="row margin-bottom-md">
<div className="col-12 col-lg-8">
<SearchBar onSearchTrigger={ term => this.videoSearch(term) } />
</div>
</div>
<div className="row margin-bottom-md">
<div className="col-12 col-lg-8">
<VideoDetail video={ this.state.selectedVideo } />
</div>
<div className="col-12 col-lg-4">
<VideoList
videos={ this.state.videos }
onVideoSelect={ selectedVideo => this.setSelectedVideo({ selectedVideo }) }
selectedVideo={ this.state.selectedVideo }
/>
</div>
</div>
</div>
);
}
} // App class end
// Take this component's generated HTML and put it on the page.
ReactDOM.render(<App />, document.querySelector('#react-render'));
我一直在网上四处寻找,并听到了一些选择。 1.我可以使用vanilla JS promise。 2. 我可以以某种方式将 JQuery 合并到我的应用程序中并使用它的 promise 函数。不幸的是,听起来我需要从 NPM 中包含一个单独的包管理器来执行此操作? 3.听说redux有promise函数。
这三个选项中哪一个是最好的/我在这里实现简单承诺的最简单方法是什么?
【问题讨论】:
标签: jquery reactjs redux promise