无法在获取请求后使用响应json数据

时间:2018-09-27 03:53:53

标签: javascript json reactjs api fetch

我正在使用react,我的目标是通过调用从Spotify api获取url的函数来将特定的URL导入href。该函数如下所示:

<a href={Spotify.getPreviewUrl(this.props.track.ID).then(results => {
                        console.log(results);
                        return results;
                    })}>Track Preview</a>

然后调用此函数,该函数从Spotify api获取网址

 getPreviewUrl(trackId) {
            return fetch(`https://api.spotify.com/v1/tracks/${trackId}`, {
                headers: {
                    Authorization: `Bearer ${usersAccessToken}`
                }
            }).then(response =>
                response.json()).then(jsonResponse => {
                console.log(jsonResponse);
                return jsonResponse.preview_url;
                });
            }

现在回到我的初始通话中:

<a href={Spotify.getPreviewUrl(this.props.track.ID).then(results => {
                        console.log(results);
                        return results;
                    })}>Track Preview</a>

console.log()值恰好是我想要的URL,但是即使我返回该值,它也不会像我想要的那样成为href URL地址。有谁知道我如何获得该值作为实际的href网址?

3 个答案:

答案 0 :(得分:0)

使用状态变量存储提取的结果并将其分配给href

constructor(){
  super();
  this.state={link:null};
}

componentDidMount(){
   Spotify.getPreviewUrl(this.props.track.ID).then(results => {
      this.setState({link:results});
    })
}
....
render(){
  return ...
        <a href={this.state.link}>Track Preview</a>
}

答案 1 :(得分:0)

尝试将componentDidMount与React state结合使用。

工作示例:https://codesandbox.io/s/9zr4znl8mo用有效的Spotify令牌替换token

import React, { Component, Fragment } from "react";
import Spinner from "./Spinner";
import ShowError from "./ShowError";
import ShowTrack from "./ShowTrack";

export default class Spotify extends Component {
  state = {
    artist: "",
    err: "",
    image: "",
    isLoading: true,
    link: "",
    token: "FAKE_TOKEN",
    trackName: "",
    trackId: "2Ll0eOXFmIeBlcybOSaQJm"
  };

  componentDidMount = () => {
    const { token, trackId } = this.state;

    fetch(`https://api.spotify.com/v1/tracks/${trackId}`, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })
      .then(res => res.json())
      .then(({ artists, name, preview_url, album: { images } }) =>
        this.setState({
          artist: artists && artists.length > 0 ? artists[0].name : null,
          link: preview_url,
          image: images && images.length > 0 ? images[0].url : null,
          isLoading: false,
          trackName: name
        })
      )
      .catch(err => this.setState({ err: err.toString(), isLoading: false }));
  };

  render = () =>
    this.state.err 
      ? <ShowError err={this.state.err} />
      : this.state.isLoading
        ? <Spinner />
        : <ShowTrack {...this.state} />
  );
}

enter image description here

答案 2 :(得分:0)

      // return a Promise from within .then() as enter code here
       const getResult = (result) => result;
       const Promise = require('bluebird');
       let promisifiedResult = Promise.promisify(getResult);


       getPreviewUrl(trackId) {
        return fetch(`https://api.spotify.com/v1/tracks/${trackId}`, 
        {
            headers: {
                Authorization: `Bearer ${usersAccessToken}`
            }
        }).then(response =>
            response.json()).then(jsonResponse => {
               return promisifiedResult (jsonResponse.preview_url);
            });
        }