0

我正在使用 react-native-ytdl 和 react-native-video

我从“react-native-ytdl”获得 youtube 播放链接,并从“react-native-video”播放

但是“react-native-ytdl”是使用异步加载组件时,第一个testvalue出来为undefined, 在这里输入图片描述

并且当异步完成时,链接被重新渲染。 在此处输入图像描述

ytdl 代码

componentDidMount(){
            
            const {route, navigation} = this.props; 
            const {gameVid} = route.params;
            
            
                const rendertest = async (gameVid) => {

        
                    const format = await ytdl(gameVid, { quality: '22'});
                    let test = JSON.stringify(format[0].url);
                        
                    return test
                    
                }
            
             
                    rendertest(gameVid).then(finalValue => {
                        console.log(typeof(finalValue)+": "+finalValue)
                        //this.state.testvalue = finalValue;
                        this.setState({
                            testvalue: finalValue,
                            
                        });
                       
                        
                    })
    
            
            
            
        }

反应原生视频代码

<Video source={{uri: this.state.testvalue}}
                            
                            
                            resizeMode = "cover"
                            isNetwork = {this.state.done}

                            style={{width: '100%', height: 250,
                                position:'absolute',
                                
                            }}
                            
        
        
                    />

视频似乎无法正常播放,因为它最初是未定义的

如何在渲染组件之前获取要加载的链接..?

4

1 回答 1

1

您可以有条件地渲染 Video 组件。这样,如果this.state.testvalue是真的,视频组件将呈现

{this.state.testvalue ? (
    <Video
        source={{uri: this.state.testvalue}}
        resizeMode="cover"
        isNetwork={this.state.done}
        style={{width: '100%', height: 250, position:'absolute'}}
    />
) : null}
于 2021-07-05T10:10:24.953 回答