简体   繁体   中英

Possible Unhandled Promise Rejection (id: 0): TypeError: Cannot read property 'title' of undefined in react-native-track-player

I created genres, each genre has an array of songs. I also have Player.js for each genre songs array, but am getting Warning and TypeError message: [Sun Apr 04 2021 05:49:58.513] WARN Possible Unhandled Promise Rejection (id: 0): TypeError: Cannot read property 'title' of undefined TypeError: Cannot read property 'title' of undefined

And when I try to change tracks I get this errors too: [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: Cannot read property 'scrollToOffset' of null TypeError: Cannot read property 'scrollToOffset' of null

How do I play the songs on each genres. I need help on this, I've been trying to solve this issue 2 days ago. Below is 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', }; });

during development when you save your code the TrackPlayer.setupPlayer() runs twice which throws an Error. To avoid this check if the Track player is setup before or not, when it is not setup then run TrackPlayer.setupPlayer() your code should look something like this:

import TrackPlayer, { State } from 'react-native-track-player';
// when you want to setup your player do it like this

// set up the player if it is not set up yet
TrackPlayer.getState().then(async (state) => {
    if (state === State.None) {
        // The player is not set up
        await TrackPlayer.setupPlayer();
    }
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM