从REST API加载的React-native Image URL未显示

时间:2018-03-12 13:05:53

标签: reactjs react-native

我的应用程序从Wordpress后端获取最新帖子,并使用文本组件和Image组件填充Listview。 Image组件URI指向名为fetchimageurl(id)

的函数
<Image 
    source={{uri: this.fetchimageurl(post.featured_media)}}
    style={{width: 400, height: 400}}
/>

函数fetchimageurl(id)获取post对象的id值,并使用特定的帖子ID命中后端API / Media端点,以返回缩略图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之前呈现组件或类似的东西有关。我在与图像组件的生命周期相关的文档中找不到多少。有人可以指出我正确的方向吗?

1 个答案:

答案 0 :(得分:6)

您无法将承诺传递给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}}
/>