TypeError:undefined不是对象(正在评估..)

时间:2020-05-07 10:10:32

标签: react-native

我编写了一个React-native项目,该项目使用REST从Spotify获取并渲染播放列表。我已经编写了一种方法,当您单击播放列表时,它将播放该播放列表,尽管在单击要播放的播放列表时遇到一个奇怪的错误。如果有人可以告诉我是什么导致了错误,我将不胜感激!预先谢谢你!

错误显示为: TypeError: _this.fetchTracks is not a function. (In '_this.fetchTracks(item.id)','_this.fetchTracks' is undefined)

这是进口商品和我的Spotify Api凭据:

import React, { Component } from 'react'
import { View, Text, Image, StyleSheet, FlatList, TouchableOpacity} from 'react-native';
import * as Font from 'expo-font';
import styled from 'styled-components';
import dimensions from '../components/ScreenSize';
import colours from '../components/Colours';
import { Audio } from 'expo-av';
import { TouchableHighlight } from 'react-native-gesture-handler';

const client_id = {Client_ID}
const client_secret = {Client_Secret}

这是该方法所在的代码的其余部分:

export default class HomeScreen extends React.Component {
    state={
      fontsLoaded:false,
    }
    async componentDidMount() {
      await Font.loadAsync({
        'montserrat-regular': require('../assets/fonts/Montserrat/Montserrat-Regular.ttf'),
        'montserrat-light': require('../assets/fonts/Montserrat/Montserrat-Light.ttf'),
        'montserrat-semibold': require('../assets/fonts/Montserrat/Montserrat-SemiBold.ttf'),
        'montserrat-bold': require('../assets/fonts/Montserrat/Montserrat-Bold.ttf'),
      }
      ).then(() => this.setState({ fontsLoaded:true }))
      this.getToken();
      this.setAudio();
    }

    constructor (props) {
        super(props)
        this.playbackInstance=null;
        this.state = {
            playing:false,
            token: '',
            DATA:[],
        };
    }

    setAudio=() => {
        Audio.setAudioModeAsync({
            allowsRecordingIOS:false,
            interruptionModeIOS: Audio.INTERRUPTION_MODE_IOS_DO_NOT_MIX,
            playsInSilentModeIOS: true,
            shouldDuckAndroid: true,
            interruptionModeAndroid: Audio.INTERRUPTION_MODE_ANDROID_DO_NOT_MIX,
            playThroughEarpieceAndroid: false,
        });
    }

    componentDidCatch(error, info)
    {
        console.log(error, info.componentStack);
    }

    getToken = async() =>
    {
        try
        {
            const getspotifytoken = await fetch("https://accounts.spotify.com/api/token",
            {
                method:'POST',
                body: `grant_type=client_credentials&client_id=${client_id}&client_secret=${client_secret}`,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            });

            const spotifytoken = await getspotifytoken.json();
            this.setState({
                token: spotifytoken.access_token
            });

            console.log(this.state.token);
        }
        catch(err)
        {
            console.log("Error fetching data", err);
        }
    }

    search = async () => {
        try
        {
            console.log("Searching: mood")
            const spotifyApiCall = await fetch(`https://api.spotify.com/v1/browse/categories/mood/playlists?country=GB&limit=50`, {
                headers: {
                    Accept: 'application/json',
                    Authorization: `Bearer ${this.state.token}`,
                    "Content-Type":'application/json'
                }
            })
            const spotify = await spotifyApiCall.json();
            console.log("Items", spotify);

            this.setState({
                DATA: spotify.playlists.items,
            })
        }
        catch (err)
        {
            console.log("Error fetching data", err);
        }
    }

    fetchTracks = async (playlistId) => {
        console.log('Playlist', playlistId)
        try
        {
            const getplaylist = await fetch(`https://api.spotify.com/v1.playlists/${playlistId}`,
            {
                method:'GET',
                headers: {
                    Accept:"application/json",
                    Authorization:`Bearer ${this.state.token}`,
                    "Content-Type":"application/json"
                }
            });

            const playlist = await getplaylist.json();
            console.log('Music', playlist.tracks.items[0].preview_url);
        }

        catch (err)
        {
            console.log("Error fetching data", err);
        }
    }

    async _loadNewPlaybackInstance(playing, track) {
        if(this.playbackInstance != null)
        {
            await this.playbackInstance.unloadAsync();
            this.playbackInstance.setOnPlaybackStatusUpdate(null);
            this.playbackInstance = null;
        }

        const source = {uri: track};
        const initialStatus = {
            shouldPlay: true,
            rate: 1.0,
            shouldCorrectPitch: true,
            volume: 1.0,
            isMuted: false
        };
        const {sound, status} = await Audio.Sound.createAsync(
            source.initialStatus);
            this.playbackInstance=sound;
            this.playbackInstance.setIsLoopingAsync(false);
            this.playbackInstance.playAsync();

        if (this.state.selected === playlistId) {
            console.log("Playing, so stop");
            this.setState({selected:null});
            this.playbackInstance.pauseAsync();
            return;
        }

        this.setState({ selected:playlistId});
        this._loadNewPlaybackInstance(true, playlist.tracks.items[0].preview_url);
        {this.state.selected === item.id && <View style = {styles.selected}><Ionicons name = "ios-play-circle" size={50} color='#bb1d68' /></View>}
    }

    render() { 
      if(!this.state.fontsLoaded ) {
        return null
      }
      return (
        <Container>
          <Titlebar>
            <Title>Music</Title>
          </Titlebar>
          <HeaderBar2>
             <Header2>Playlists for your Mood</Header2>
             <TouchableOpacity
             onPress={() => this.search()}>
               <Header3>Click here to get Playlists!</Header3>
             </TouchableOpacity>
             </HeaderBar2>
          <View style={{flex:1}}>
            {
              this.state.DATA.length == 0 &&
              <Text></Text>
            }

              <FlatList
              data = {this.state.DATA}
              renderItem={item}
              keyExtractor = {item.id}
              extraData = {this.state}
              numColumns ={2}
              />
          </View>
        </Container>
      );
    }
  }

0 个答案:

没有答案