reactjs - 在本机反应中获取轮播中的动态图像
问题描述
我正在使用react-native-image-gallery。其中这些图像的 url 已经在images
数组中以状态给出。但我想动态加载这些从 API 获取的图像,如代码所示。我能够将这些路径保存为状态,但是要显示这些图像,它需要域名为https://xyz.in/
. 我被卡住了如何显示那些动态获取的图像。
请帮忙。
代码:
constructor(props) {
super(props);
this.state = {
images: [
{ source: { uri: 'http://i.imgur.com/30s12Qj.jpg' } },
{ source: { uri: 'http://i.imgur.com/4A1Q49y.jpg' } },
{ source: { uri: 'http://i.imgur.com/JfVDTF9.jpg' } },
{ source: { uri: 'http://i.imgur.com/Vv4bmwR.jpg' } }
],
fetched_images:[]
};
}
async componentDidMount() {
return fetch(`https://xyz.in/api/shop/username`,
{
method: "GET",
headers: {
'Authorization': `JWT ${DEMO_TOKEN}`
}
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
fetched_images: responseJson.all_images,
});
})
}
render() {
return (
<View>
<Gallery
style={{ height:300, width:'100%', backgroundColor: '#696969'}}
images={this.state.images}
errorComponent={this.renderError}
onPageSelected={this.onChangeImage}
initialPage={0}
/>
</View>
);
}
json数据:
"all_images": [
{
"image": "/media/All%20Product%20Images/20150415_093955_2.jpg"
},
{
"image": "/media/All%20Product%20Images/amshoe.jpg"
},
{
"image": "/media/All%20Product%20Images/ckramii.jpg"
}
]
解决方案
您可以通过制作格式化程序功能来格式化图像
const DomainName = 'https://xyz.in'
const formatImages = (images) => {
return images.map(image => {
return {source: {uri : `${DomainName}/${image}`}}
})
}
.then((responseJson) => {
const formattedImages = this.formatImages(responseJson.all_images)
this.setState({
fetched_images: formattedImages,
});
<Gallery
...// Other props
images={this.state.fetched_images}
/>
推荐阅读
- google-cloud-platform - 以增量方式将 Cloud SQL 转换为 BigQuery
- c++ - 在 C++ 中创建 NSApplication
- javascript - 如何禁用后退按钮浏览器
- algorithm - 真实世界路径的数据结构
- ionic-framework - 在 ionic 应用程序中访问 InAppBrowser 的标记
- python - 结束后如何循环此代码以及如何使代码的 Y/N 部分工作?
- python - Python拼接列表在向后工作时不包含第一个元素
- python - 在 Python 中,与大多数语言一样,您使用 0 访问列表中的第一项。但是从 1 开始会是更好的选择吗?
- python - 使用按钮选择中断 For 循环
- r - 如何在 R 中插入数据框的每一行?