首页 > 解决方案 > 使用从 Web API 检索到的图像 URL 链接在视图中显示图像

问题描述

在网上搜索后,我找到了一些不错的代码来满足我的要求。我已经成功地从我的 Web API 中检索到数据,并在一个 FlatList 的页面视图中显示了内容。但是,从 API 检索到的图像 URL 没有被处理,我不知道为什么。

这是我的结果

图片

/**
     * Sample React Native App
     * https://github.com/facebook/react-native
     * @flow
     */

    import React, { Component } from 'react';
    import {
      Platform,
      StyleSheet,
      Text,
      View,
      FlatList,
      ActivityIndicator,
      Image
    } from 'react-native';
    //import data from './json/FetchJsonDataExample.json';

    export default class App extends Component<Props> {
      constructor(props) {
        super(props);

        this.state = {
          isLoading: true, // check if json data (online) is fetching
          dataSource: [], // store an object of json data
        };
      }

      componentDidMount() {
        return fetch("https://www.apakataorang.com/wp-json/wp/v2/posts?per_page=20")
              .then((response) => response.json())
              .then((responseJson) => {
                // set state value
                this.setState({
                  isLoading: false, // already loading
                  dataSource: responseJson
                });
              })
              .catch((error) => {
                ToastAndroid.show(error.toString(), ToastAndroid.SHORT);
              });
      }

      render() {
        // show waiting screen when json data is fetching
        if(this.state.isLoading) {
          return(
            <View style={{flex: 1, padding: 20}}>
              <ActivityIndicator/>
            </View>
          )
        }

        return(
          <View style={{flex: 1, paddingTop:30}}>
            <FlatList
              data={this.state.dataSource}
              renderItem={({item}) => {
                return (
                  <View>
                    <Text style={styles.info}>{item.title.rendered}</Text>
                    <Image
                    source={{uri: 'item.jetpack_featured_media_url'}}
                    style={{width:'100%', height: 200, resizeMode : 'stretch'}}
                    />
                    <Text style={styles.info}>{item.jetpack_featured_media_url}</Text>
                  </View>
                )
              }}
              keyExtractor={(item, index) => index.toString()}
            />
          </View>
        );
      }
    }

    const styles = StyleSheet.create({
      info: {
        fontSize: 20,
      }
    });

理想情况下,我希望图像显示在视图上。

标签: imageapireact-native

解决方案


从 Image 组件的源道具中删除单引号,如下所示:

<Image
    source={{uri: item.jetpack_featured_media_url}}
    style={{width:'100%', height: 200, resizeMode : 'stretch'}}
/>

如果您将'item.jetpack_featured_media_url'(使用单引号)设置为 URI,它会将其视为路径本身


推荐阅读