首页 > 解决方案 > 在本机反应中获取轮播中的动态图像

问题描述

我正在使用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"
    }
]

标签: reactjsreact-nativecarouselreact-native-image

解决方案


您可以通过制作格式化程序功能来格式化图像

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}
  />

推荐阅读