在线搜索后,我发现了一些不错的代码可以满足我的要求。我已经成功地从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,
}
});
理想情况下,我希望图像显示在视图上。
答案 0 :(得分:2)
从Image组件的源prop中删除单引号,如下所示:
<Image
source={{uri: item.jetpack_featured_media_url}}
style={{width:'100%', height: 200, resizeMode : 'stretch'}}
/>
如果您将URI设置为'item.jetpack_featured_media_url'
(用单引号引起来),它将被视为路径本身