我的应用程序从 Wordpress 后端获取最新帖子,并使用文本组件和图像组件填充 ListView 。 Image 组件 URI 指向一个名为 fetchimageurl(id) 的函数
<Image
source={{uri: this.fetchimageurl(post.featured_media)}}
style={{width: 400, height: 400}}
/>
函数 fetchimageurl(id) 获取帖子对象的 id 值,并使用特定的帖子 ID 访问后端 API/媒体端点以返回缩略图 URL。
fetchimageurl(id){
fetch('http://ipaddress/sitename/wp-json/wp/v2/media/'+id)
.then(function(response){
if (!response.ok){
console.log("Rewrite error handling - Draft code")
return
}
response.json().then(function(data){
return data.media_details.sizes.medium_large.source_url
})
})
}
fetch 方法工作正常,可以正确解析和返回 URL,但是,一旦解析的 URL 传回,Image 组件就无法显示图像。
我猜这个问题与 RN 在函数返回 URL 或类似的东西之前呈现组件有关。我在与图像组件生命周期相关的文档中找不到太多内容。有人可以指出我正确的方向吗?
最佳答案
您不能将 Promise 传递给 uri
。
在组件的某处调用 Promise,然后在组件的状态中设置结果 URI:
this.fetchimageurl(post.featured_media).then(res => {
this.setState({imageUri: res})
})
然后在渲染中:
<Image
source={{uri: this.state.imageUri}}
style={{width: 400, height: 400}}
/>
关于reactjs - 从 REST API 加载的 react native 图像 URL 未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49236023/