android - 无法从 React Native 中的 JSON 数组正确获取数据
问题描述
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
.
仅从JSON 数组中responseJson.data[0].post_type
获取第一个对象。post_type
我也加this.state.post_type
进去了extraData
。
请告诉我如何从 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, }}
/>
}
);
}
解决方案
你能检查一下这是否有效吗?
<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 ) => {
if( item.post_type === "image")
return(
<Image
//source={this.props.item.image}
source={image}
//source={{ uri: strings.sourceUri+"userimage/"+item.imgSrc }}
style={styles.photo}
/>);
else
return(
<Video
source={video}
ref={(ref) => { this.player = ref }}
style={{ width: 300, height: 350, }}
/>);
}
还可以看到,在<Image>
源代码之后,我给出了两种来源方式
推荐阅读
- c# - 在更改日志之前获取实体
- python - 从字符串中提取字符并在 Python 中形成新列
- python - 如何使用 numpy 将多个数据分别保存在单个输出文件中
- ruby-on-rails - 如果从辅助方法 rails 更改,则不会显示 I18n 转换的值
- react-native - 视图换行到下一行时如何使用marginTop?
- anaconda - 错误 anaconda_api.is_vscode_available:956
- postman - postman.setNextRequest() 中的目标请求无法设置环境变量
- autoconf - 为 r 包编写 `configure` 文件
- java - 多个分隔符,并希望使用正则表达式将其中一个分隔符包含在字符串中
- python - tensorflow,feed_dict 错误,ValueError:无法输入形状的值