在React Native中在轮播中获取动态图像

时间:2018-09-10 14:11:21

标签: reactjs react-native carousel react-native-image

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

1 个答案:

答案 0 :(得分:1)

您可以通过设置格式化程序功能来格式化图像

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}
  />
相关问题