首页 > 解决方案 > 可能未处理的 Promise Rejection (id: 0): TypeError: Cannot read property 'title' of undefined in react-native-track-player

问题描述

我创建了流派,每个流派都有一系列歌曲。我也有每个流派歌曲数组的 Player.js,但收到警告和 TypeError 消息:[Sun Apr 04 2021 05:49:58.513] WARN Possible Unhandled Promise Rejection (id: 0): TypeError: Cannot read property 'title'未定义的类型错误:无法读取未定义的属性“标题”

当我尝试更改曲目时,我也收到此错误:[Sun Apr 04 2021 05:49:58.676] LOG track id -1 index 3 [Sun Apr 04 2021 05:49:58.690] WARN Possible Unhandled Promise Rejection (id: 1): TypeError: 无法读取 null 的属性 'scrollToOffset' TypeError: 无法读取 null 的属性 'scrollToOffset'

我如何播放每种流派的歌曲。我需要帮助,两天前我一直在尝试解决这个问题。下面是 hipHopPlayerScreen.js:

import React, {useRef, useEffect, useState} from 'react';
import {
  View,
  SafeAreaView,
  Text,
  Image,
  FlatList,
  Dimensions,
  Animated,
  StyleSheet,
  TouchableOpacity,
} from 'react-native';

import { useNavigation } from '@react-navigation/native';

import TrackPlayer, {
  Capability,
  useTrackPlayerEvents,
  usePlaybackState,
  TrackPlayerEvents,
  STATE_PLAYING,
  Event,
} from 'react-native-track-player';

import hiphopsongs from '../../components/TracksData/hipHopData';
import Controller from '../../components/Controller';
import SliderComp from '../../components/SliderComp';
import SimpleLineIcons from 'react-native-vector-icons/SimpleLineIcons';

const {width, height} = Dimensions.get('window');

export default function HipHopPlayerScreen() {

  const navigation = useNavigation();

  const scrollX = useRef(new Animated.Value(0)).current;

  const slider = useRef(null);
  const isPlayerReady = useRef(false);
  const index = useRef(0);

  const [hipHopsongIndex, setHipHopSongIndex] = useState(0);
  

  const isItFromUser = useRef(true);

  const position = useRef(Animated.divide(scrollX, width)).current;
  const playbackState = usePlaybackState();

  useEffect(() => {
    scrollX.addListener(({value}) => {
      const val = Math.round(value / width);

      setHipHopSongIndex(val);
    });

    TrackPlayer.setupPlayer().then(async () => {
      console.log('Player ready');
   
      await TrackPlayer.reset();
      await TrackPlayer.add(hiphopsongs);
      TrackPlayer.play();
      isPlayerReady.current = true;

      await TrackPlayer.updateOptions({
        stopWithApp: false,
        alwaysPauseOnInterruption: true,
        capabilities: [
          Capability.Play,
          Capability.Pause,
          Capability.SkipToNext,
          Capability.SkipToPrevious,
        ],
      });
      TrackPlayer.addEventListener(Event.PlaybackTrackChanged, async (e) => {
        console.log('song ended', e);

        const trackId = (await TrackPlayer.getCurrentTrack()) - 1;

        console.log('track id', trackId, 'index', index.current);

        if (trackId !== index.current) {
          setHipHopSongIndex(trackId);
          isItFromUser.current = false;

          if (trackId > index.current) {
            goNext();
          } else {
            goPrv();
          }
          setTimeout(() => {
            isItFromUser.current = true;
          }, 200);
        }
      });

     
      TrackPlayer.addEventListener(Event.RemoteDuck, (e) => {
     
        if (e.paused) {
         
          TrackPlayer.pause();
        } else {
          TrackPlayer.play();
        }
      });
    });

    return () => {
      scrollX.removeAllListeners();
      TrackPlayer.destroy();

      // exitPlayer();
    };
  }, []);

  // change the song when index changes
  useEffect(() => {
    if (isPlayerReady.current && isItFromUser.current) {
      TrackPlayer.skip(hiphopsongs[hipHopsongIndex].id)
        .then((_) => {
          console.log('changed track');
        })
        .catch((e) => console.log('error in changing track ', e));
    }
    index.current = hipHopsongIndex;
  }, [hipHopsongIndex]);

  const exitPlayer = async () => {
    try {
      await TrackPlayer.stop();
    } catch (error) {
      console.error('exitPlayer', error);
    }
  };

  const goNext = async () => {
    slider.current.scrollToOffset({
      offset: (index.current + 1) * width,
    });

    await TrackPlayer.play();
  };
  const goPrv = async () => {
    slider.current.scrollToOffset({
      offset: (index.current - 1) * width,
    });

    await TrackPlayer.play();
  };

  const renderItem = ({index, item}) => {
    return (
      <Animated.View
        style={{
          alignItems: 'center',
          width: width,
          transform: [
            {
              translateX: Animated.multiply(
                Animated.add(position, -index),
                -100,
              ),
            },
          ],
        }}>
        <Animated.Image
          source={item.artwork}
          style={{width: 320, height: 320, borderRadius: 5}}
        />
      </Animated.View>
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <SafeAreaView style={{height: 320}}>
        <Animated.FlatList
          ref={slider}
          horizontal
          pagingEnabled
          showsHorizontalScrollIndicator={false}
          scrollEventThrottle={16}
          data={hiphopsongs}
          renderItem={renderItem}
          keyExtractor={(item) => item.id}
          onScroll={Animated.event(
            [{nativeEvent: {contentOffset: {x: scrollX}}}],
            {useNativeDriver: true},
          )}
        />
      </SafeAreaView>
      <TouchableOpacity 
        style={styles.genreContainer}
        onPress={() => navigation.navigate('Genre')}
      >
        <SimpleLineIcons name="playlist" size={20} color='#fff' />
        <Text style={styles.genre}> Genre</Text>
      </TouchableOpacity>
      <View>
        <Text style={styles.title}>{hiphopsongs[hipHopsongIndex].id.title}</Text>
        <Text style={styles.artist}>{hiphopsongs[hipHopsongIndex].id.artist}</Text>
      </View>

      <SliderComp />

      <Controller onNext={goNext} onPrv={goPrv} />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    justifyContent: 'space-evenly',
    alignItems: 'center',
    height: height,
    maxHeight: 600,
    backgroundColor: '#030303'
  },
  genreContainer: {
    flexDirection: 'row',
  },
  genre: {
    fontSize: 18,
    textAlign: 'center',
    fontWeight: '600',
    textTransform: 'capitalize',
    color: '#ffffff',
  },
  title: {
    fontSize: 28,
    textAlign: 'center',
    fontWeight: '600',
    textTransform: 'capitalize',
    color: '#ffffff',
  },
  artist: {
    fontSize: 18,
    textAlign: 'center',
    color: '#ffffff',
    textTransform: 'capitalize',
  },
});

标签: javascriptreactjsreact-nativereact-native-track-player

解决方案


推荐阅读