Как получить объекты в массиве в реагировать родной, используя плоский список swiper - PullRequest
0 голосов
/ 10 января 2020

___ Вот мой код ____

import React, { PureComponent } from 'react';
import { Text, Dimensions, Image, StyleSheet, View ,FlatList} from 'react-native';

import SwiperFlatList from 'react-native-swiper-flatlist';
import { Icon } from 'react-native-elements';
const URI = 'some Url';

export default class ProductDetailsSwiper extends PureComponent {
    constructor(props) {
    super(props);
        //this.params = this.props.navigation.state.params;

    this.state = {
      achhamall: []
    };
  }
  componentDidMount() {
    this.fetchData();
  }

 async fetchData() {
//let AccessToken = this.params.AccessToken;
    try {
    let response = await fetch(URI ,{
                              method: 'Post',
                              headers: {
                                'Accept': 'application/json',
                                'Content-Type': 'application/x-www-form-urlencoded', 
                              },

                                 body: 'product_id=83',

                            });
         let responseJson = await response.json();
          if (response.status >= 200 && response.status < 300) {

                     this.setState({
                      achhamall : responseJson.images                   
                     })
          console.log('data fetch ' + responseJson.products);
                               let images = responseJson.images;
                                console.log('data' + images);
          }else{
             console.log('responseJson');
          }
        } catch(error) {
           console.log("error response: " + error);
          }
   }

  render() {
    return (
      <View style={styles.container}>
        <SwiperFlatList
        paginationStyle={styles.dotStyle}
          // autoplay
          //autoplayDelay={2}
          // autoplayLoop
          //index={2}
           showPagination
        >

                    <FlatList
          data={this.state.achhamall}
          keyExtractor= {(item) => {
            return item.id.toString();
          }}

          renderItem={(post) => {
         const item = post.item;
          return(
          <View style={[styles.child, {  }]}>
          <View
                      style={{
                        height: 30,
                        width: 30,
                        backgroundColor: 'red',
                        borderRadius: 15,
                        justifyContent: 'center',
                        alignItems: 'center',
                        top:-70,
                        right:10,
                      }}>
                      <Text style={{fontSize: 12, color: '#FFFFFF'}}>20%</Text>
                      <Text style={{fontSize: 10, color: '#FFFFFF'}}>OFF</Text>
                    </View>
                 <Image
                      style={{height:height/4, width:width/2, resizeMode: 'cover'}}
                      source={{uri: item.src}}
                    />
                     <View style={{ top:-70,left:10}}>
                    <Icon name="favorite" />
                    </View>
          </View>

       )
        }}/>

        </SwiperFlatList>
      </View>
    );
  }
}

export const { width, height } = Dimensions.get('window');

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent:"center",
    alignItems:"center",
    backgroundColor: 'white',
  },
  dotStyle:{
// width:0,
// height:height/4,
color:"green",
//backgroundColor:"red",
top:180

  },
  child: {
   // height: height * 0.5,
    width,
    justifyContent:"center",
    alignItems:"center",
    flexDirection:"row"
  },
  text: {
   // fontSize: width * 0.5,
    textAlign: 'center',
  },
});

мой ответ в json, чтобы показать в реагировать родной ___

"product": {
    "id_product": "83",
    "quantity": "0",
    "allow_out_of_stock": 0,
    "name": "Mini USB Cable - Android",
    "price": "₹109.00",
    "discount_price": "",
    "discount_percentage": "",
    "minimal_quantity": "1",
    "images": [
        {
            "src": "https://www.achhamall.com/staging-achhamall.com/image/cache/catalog/usbcable/DSC_8902-200x200.jpg"
        },
        {
            "src": "https://www.achhamall.com/staging-achhamall.com/image/cache/catalog/microusb/MiniUSBGreeAThumbnail-200x200.jpg"
        },
        {
            "src": "https://www.achhamall.com/staging-achhamall.com/image/cache/catalog/microusb/DSC_8904-200x200.jpg"
        },
        {
            "src": "https://www.achhamall.com/staging-achhamall.com/image/cache/catalog/microusb/DSC_8903-200x200.jpg"
        },
        {
            "src": "https://www.achhamall.com/staging-achhamall.com/image/cache/catalog/microusb/DSC_8902-200x200.png"
        }
    ],

, как использовать условие Flatlist в swiperflatlist, получить изображение и сделать это swipeable ...

и как назначить ключ и в swiperflatlist для выборки coz при поиске многими способами, которые я нашел, но при его реализации показывает ошибку инвариантного нарушения: пытался получить кадр для индекса вне диапазона NaN так как это исправить?

Ответы [ 3 ]

1 голос
/ 15 января 2020

Ошибка вашего кода при установке изображения в состояние. В вашем ответе изображение приходит как ответ Json .product.image, но вы используете его как ответ Json .image. Вот ваш код

 this.setState({
     achhamall : responseJson.images                   
  })

Он должен быть как ниже

this.setState({
          achhamall : responseJson.product.images                   
 })
0 голосов
/ 11 января 2020
  <View style={styles.container}>
          <SwiperFlatList
         autoplay
        autoplayDelay={2}
        autoplayLoop
        data={this.state.achhamall}
        renderItem={({item}) => // Standard Image
                       <View style={[styles.child, {  }]}>
          <View
                      style={{
                        height: 30,
                        width: 30,
                        backgroundColor: 'red',
                        borderRadius: 15,
                        justifyContent: 'center',
                        alignItems: 'center',
                        top:-70,
                        right:10,
                      }}>
                      <Text style={{fontSize: 12, color: '#FFFFFF'}}>20%</Text>
                      <Text style={{fontSize: 10, color: '#FFFFFF'}}>OFF</Text>
                    </View>
                 <Image
                      style={{height:height/4, width:width/2, resizeMode: 'cover'}}
                      source={{uri: item.src}}
                    />
                     <View style={{ top:-70,left:10}}>
                    <Icon name="favorite" />
                    </View>
                    </View>
                        }
        showPagination
      />
      </View>

вы можете использовать данные как состояние в плоском списке swiper и получать изображения

0 голосов
/ 11 января 2020

achhamall: ответ Json .product.images ответ есть в продуктах? так что добавь это ....

...