【发布时间】:2019-06-25 21:11:53
【问题描述】:
showPosts = async () => {
var userID = await AsyncStorage.getItem('userID');
fetch(strings.baseUri+"getPostWithUserID", {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"user_id": userID
})
})
.then((response) => response.json())
.then((responseJson) => {
let jsonObj = JSON.parse(JSON.stringify(responseJson));
if (jsonObj.status=="true") {
this.setState({
data: responseJson.data,
imageSrc: responseJson.data[0].imgSrc,
post_type: responseJson.data[0].post_type,
videoSrc: responseJson.data[0].video,
});
}
})
.catch((error) => {
console.error(error);
});
}
我正在从 api 获取数据,然后在 Flatlist 中使用它。
这是我alert(responseJson.data) 时得到的。
现在,我的responseJson.data[0].imgSrc 和responseJson.data[0].video 迭代每个对象,我可以通过Flatlist 在我的屏幕上显示它。但responseJson.data[0].post_type 并非如此。
responseJson.data[0].post_type 仅从 JSON 数组中获取第一个对象的 post_type。我还在extraData 中添加了this.state.post_type。
请告诉我如何从 Json 数组中访问数据,然后在 Flatlist 中使用它。
更新代码
<FlatList
data={this.state.data}
renderItem={ ({item,index}) => this._renderItem(item,index) }
extraData={[ this.state.data, this.state.checked, this.state.post_type ]}
/>
_renderItem = ( item, index ) => {
return(
{ item.post_type == "image" ?
<Image
//source={this.props.item.image}
source={image}}
//source={{ uri: strings.sourceUri+"userimage/"+item.imgSrc }}
style={styles.photo}
/>
:
<Video
source={video}
ref={(ref) => { this.player = ref }}
style={{ width: 300, height: 350, }}
/>
}
);
}
【问题讨论】:
-
JSON.parse(JSON.stringify(responseJson));真的很奇怪,虽然这不是你的问题。有什么意义? -
当
post_type为image时,我希望我的图像显示在屏幕上,当post_type为video时,我希望我的图像显示在屏幕上的视频上。但是post_type只能从json数组的第一个对象访问。 -
你能告诉我们你的渲染方法吗?
-
@ShubhamBisht 那么你应该尝试正确解释这个问题。我什么都听不懂????
-
@ShubhamBisht 你真的需要努力解释你的问题。除非您努力发布经过精心编辑的问题,否则没有人可以帮助您。一些问得好问题的例子 - stackoverflow.com/q/54257762/6141587 或 stackoverflow.com/q/50603994/6141587
标签: android reactjs react-native react-native-flatlist