问题描述
我正在使用 react-native-ytdl 和 react-native-video
我从“react-native-ytdl”获得 youtube 播放链接,我从“react-native-video”播放
但是“react-native-ytdl”正在使用异步 加载组件时,第一个测试值显示为未定义, enter image description here
当异步完成时,链接会重新渲染。 enter image description here
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,});
})
}
react-native-video 代码
<Video source={{uri: this.state.testvalue}}
resizeMode = "cover"
isNetwork = {this.state.done}
style={{width: '100%',height: 250,position:'absolute',}}
/>
视频似乎不能正常播放,因为它最初是未定义的
解决方法
您可以有条件地渲染视频组件。
这样,如果 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}