如何在React Native组件渲染前完成react-native-ytdl的视频链接加载
解决方案
你不需要强制让异步请求在组件渲染前完成,通过状态管理和条件渲染即可解决初始值异常问题,具体修改如下:
1. 初始化State配置
先给组件State添加加载状态和合理初始值:
state = { testvalue: null, isLoading: true, done: false }
2. 修正ytdl调用的多余逻辑
你当前对返回的url做了JSON.stringify处理,会导致url两端多出无用的双引号,直接取原生字符串即可:
componentDidMount(){ const {route, navigation} = this.props; const {gameVid} = route.params; const rendertest = async (gameVid) => { const format = await ytdl(gameVid, { quality: '22'}); // 去掉JSON.stringify,直接返回url原始值 return format[0].url; } rendertest(gameVid).then(finalValue => { console.log(typeof(finalValue)+": "+finalValue) this.setState({ testvalue: finalValue, isLoading: false, done: true }); }) // 补充异常捕获逻辑,处理请求失败场景 .catch(err => { console.error('获取视频链接失败', err); this.setState({isLoading: false}); }) }
3. 渲染部分加条件判断
初始加载时先渲染占位元素,等视频链接获取成功后再渲染Video组件:
render() { const { isLoading, testvalue } = this.state; if (isLoading) { // 这里可以替换为你自己的加载动画/占位图 return <View style={{width: '100%', height: 250, backgroundColor: '#000', justifyContent: 'center', alignItems: 'center'}}> <Text style={{color: '#fff'}}>视频加载中...</Text> </View> } // 加载完成但无有效链接时渲染错误提示 if (!testvalue) { return <View style={{width: '100%', height: 250, backgroundColor: '#000', justifyContent: 'center', alignItems: 'center'}}> <Text style={{color: '#fff'}}>视频加载失败</Text> </View> } // 只有拿到有效链接时才渲染视频组件 return ( <Video source={{uri: testvalue}} resizeMode = "cover" isNetwork = {this.state.done} style={{ width: '100%', height: 250, position:'absolute', }} /> ) }
内容的提问来源于stack exchange,提问作者munhyok
相关产品推荐
相关产品推荐

