如何处理response.item未定义?

问题描述 投票:0回答:1

虽然我绑定了getNowPlaying,但还是出现了下面的错误,谁能帮帮我,是不是我的代码中遗漏了什么?我尝试导入SpotifyWebApi的方式是否有误?

enter image description here

下面是导致问题的代码。

import React, { Component } from 'react';
import './App.css';

import SpotifyWebApi from 'spotify-web-api-js';
const spotifyApi = new SpotifyWebApi();

class App extends Component {
  constructor(props){
    super(props);
    const params = this.getHashParams();
    const token = params.access_token;
    if (token) {
      spotifyApi.setAccessToken(token);
    }
    this.state = {
      loggedIn: token ? true : false,
      nowPlaying: { name: 'Not Checked', albumArt: '' }
    }
    this.getNowPlaying=this.getNowPlaying.bind(this);
  }
  getNowPlaying(){
    spotifyApi.getMyCurrentPlaybackState()
      .then((response) => {
        this.setState({
          nowPlaying: { 
              name: response.item.name, 
              albumArt: response.item.album.images[0].url
            }
        });
      })
  }
  render() {
    return (
      <div className="App">
        <a href='http://localhost:8888' > Login to Spotify </a>
        <div>
          Now Playing: { this.state.nowPlaying.name }
        </div>
        </div>
    );
  }
}

export default App;
reactjs this bind spotify
1个回答
0
投票

根据Spotify的文档

响应 一个成功的请求将返回一个200 OK的响应代码,其中包含一个json有效载荷,该有效载荷包含当前播放的轨道或情节及其上下文的信息(见下文)。返回的信息是最后的已知状态,这意味着如果一个不活动的设备是最后一个执行播放的设备,则可能会返回。

当没有找到可用的设备时,请求将返回一个200 OK的响应,但没有数据填充。

当当前没有播放曲目时,请求将返回一个204 NO CONTENT响应,但没有有效载荷。

如果启用了private session,响应将是一个204 NO CONTENT和一个空的payload。

这意味着即使你的请求成功了(200 OK),响应也可能是空的,所以你需要通过检查响应是否为空来进行防御性编程

我不确定请求返回的具体对象是什么,但你可以这样做。

  spotifyApi.getMyCurrentPlaybackState()
  .then((response) => {
    this.setState({
      nowPlaying: { 
        name: response && response.item && response.item.name, 
        albumArt:  response && response.item && response.item.album && response.item.album.images.length > 0 && response.item.album.images[0].url
      }
    });
  })

这里的问题是你所需要的属性是深度嵌套的,而且你需要检查图片数组的长度是否大于0,所以可能一个更好的方法是将所有的响应对象存储在状态中,然后在渲染时检查它。

如果这不可能,你可以使用可选链,但你必须使用babel插件。https:/babeljs.iodocsenbabel-plugin-proposal-optional-chaining。

然后你就可以做

  spotifyApi.getMyCurrentPlaybackState()
  .then((response) => {
    this.setState({
      nowPlaying: { 
        name: response?.item?.name, 
        albumArt: response?.item?.album?.images[0].url
      }
    });
  })
© www.soinside.com 2019 - 2024. All rights reserved.