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

u0sqgete  于 2023-11-20  发布在  其他
关注(0)|答案(3)|浏览(116)

我使用的是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获取URL的函数:

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 URL吗?

gj3fmq9x

gj3fmq9x1#

使用状态变量存储fetch的结果并将其分配给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>
}

字符串

k4aesqcs

k4aesqcs2#

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

字符串

iq3niunx

iq3niunx3#

尝试将componentDidMount与React state结合使用。
工作示例:https://codesandbox.io/s/9zr4znl8motoken替换为有效的Spotify令牌!

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

字符串
x1c 0d1x的数据

相关问题