javascript - ReactJS componentDidMount、Fetch Spotify API 和 Promise

标签 javascript api reactjs

我正在学习如何使用 ReactJS、Spotify API 和 Promise。我正在尝试在 Spotify 上获取音乐家的顶级专辑并播放 30 秒的轨道。

我正在使用名为 spotify-web-api-node 的 Spotify 软件包我认为我不了解 React 或 JS 的一些基本知识。 语法错误:意外的 token ,预期 ( (11:8)

从'react'导入React;

import SpotifyWebApi from 'spotify-web-api-node';
require('dotenv').config();


export default class SpotifyComponent extends React.Component {
  // Create the api object with the credentials
  const spotifyApi = new SpotifyWebApi({
    clientId : process.env.REACT_APP_SPOTIFY_CLIENT_ID,
    clientSecret : process.env.REACT_APP_SPOTIFY_CLIENT_SECRET
  });
// Save the access token so that it's used in future calls
  componentDidMount() {
    **(11:8)** --> return spotifyApi = new Promise((resolve, reject) => {
      spotifyApi.clientCredentialsGrant()

      .then( => (data) {
        console.log('The access token expires in ' + data.body['expires_in']);
        console.log('The access token is ' + data.body['access_token']);
      });

      // using Promises through Promise, Q or when - get Elvis' albums in range [20...29]
      spotifyApi.getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE', {limit: 10, offset: 20})
        .then(function(data) {
          console.log('Album information', data);
        }, function(err) {
          console.error(err);
        });
    });

    SpotifyWebApi.setPromiseImplementation(Q);
  }
}

最佳答案

您使用 spotify-api 提供的 promise 的方式是正确的。但是,您不应从 componentDidMount 返回 PromiseReact 对它没有任何用处。

相反,只需在 componentDidMount 中运行基于 promise 的函数即可。

componentDidMount() {

  // the next line will actually trigger the promise to run
  spotifyApi.clientCredentialsGrant()
    .then((data) => { // this line was missing "=>" in your original code
      console.log('The access token expires in ' + data.body['expires_in']);
      console.log('The access token is ' + data.body['access_token']);
    });

  // the next line also triggers a promise to run
  spotifyApi.getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE', {limit: 10, offset: 20})
    .then(function(data) {
      console.log('Album information', data);
    }, function(err) {
      console.error(err);
    });
}

您还可以在导入后立即将 Q 设置为 promise 提供者。

import SpotifyWebApi from 'spotify-web-api-node';
SpotifyWebApi.setPromiseImplementation(Q);

关于javascript - ReactJS componentDidMount、Fetch Spotify API 和 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44120075/

相关文章:

ruby-on-rails - Rails 中的 API secret 生成

javascript - 在 ReactJS 中从子类访问父类方法

javascript - 要使用数组值更新的对象键值

javascript - 将整个对象传递给 ng-grid 中的 cellFilter 函数

javascript - 遍历可观察数组并更新计算值

android - 根对象与否? API 响应的最佳实践是什么?

node.js - REST API 的 Flash 消息

javascript - 在异步函数中执行 createStore 时未定义存储?

reactjs - 在 React Native 中将 blob 转换为图像?

javascript - 悬停在图像 map 上时颜色反转