React Native如何循环渲染图像并从API中跳过空对象
我有这样的api :
{
"success": true,
"result": [
{
"localityno": "01",
"ocationname": "Sushi xA",
"image1": "www.abc.com/abc1.jpg",
"image2": "www.abc.com/abc2.jpg",
"image3": "www.abc.com/abc3.jpg",
"image4": "www.abc.com/abc4.jpg",
"image5": "www.abc.com/abc5.jpg",
},
{
"localityno": "02",
"ocationname": "Park Zoo",
"image1": "www.abc.com/w1.jpg",
"image2": "www.abc.com/w2.jpg",
"image3": "", <<<<<<< it's null *****
"image4": "www.abc.com/w4.jpg",
"image5": "", <<<<<<< it's null *****
},
]
}
这是我的静态渲染代码: 如果图片网址为空
,则返回空白图片我想循环并跳过空对象
谢谢。
componentWillMount() {
return fetch("www.myservice.com/endpoint")
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
isLoading: false,
dataSource: ds.cloneWithRows(responseJson.result),
}, function() {
});
})
.catch((error) => {
alert("0 : Recrods On This Module ")
});
}
render() {
return (
<View style={{flex: 1, padding: 7,overflow: 'hidden'}}>
<ListView
enableEmptySections={true}
dataSource={this.state.dataSource}
renderRow={
(rowData) =>
<Image source={{uri: rowData.image1}} style={{width: 100, height: 100}} />
<Image source={{uri: rowData.image2}} style={{width: 100, height: 100}} />
<Image source={{uri: rowData.image3}} style={{width: 100, height: 100}} />
<Image source={{uri: rowData.image4}} style={{width: 100, height: 100}} />
<Image source={{uri: rowData.image5}} style={{width: 100, height: 100}} />
}
/>
</View>
);
}
}
export default Feed;
答案 0 :(得分:1)
您可以简单地创建一个动态构建项目并跳过空图像的函数。像这样:
(rowData) => {
let items = [];
for (let i = 1; i <= 5; i++) {
const key = 'image' + i;
const uri = rowData[key];
if (!uri) continue;
items.push(<Image key={key} source={{uri: uri}} style={{width: 100, height: 100}} />);
}
return <View>{items}</View>
}