ReactJS componentDidMount,获取Spotify API和Promise

时间:2017-05-22 18:47:58

标签: javascript api reactjs

我正在学习如何使用ReactJS,Spotify API和Promise。我试图在Spotify上获取音乐家热门专辑并播放30秒的曲目。

我使用名为spotify-web-api-node的Spotify软件包我认为我并不了解React或JS的基本内容。 Syntax error: Unexpected token, expected ( (11:8)

导入来自'反应&#39 ;;

的反应
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);
  }
}

2 个答案:

答案 0 :(得分:1)

您使用spotify-api提供的承诺的方式是正确的。但是,您不应该从Promise返回componentDidMountReact对此没有任何用处。

而只是在componentDidMount内运行基于承诺的函数。

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设置为承诺提供商。

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

答案 1 :(得分:0)

你不能在类这样的类中定义const

您应该将其移到外面或删除const

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

export default class SpotifyComponent extends React.Component {

export default class SpotifyComponent extends React.Component {
  // Create the api object with the credentials
  spotifyApi = new SpotifyWebApi({
    clientId : process.env.REACT_APP_SPOTIFY_CLIENT_ID,
    clientSecret : process.env.REACT_APP_SPOTIFY_CLIENT_SECRET
  });