Инвариантное нарушение: попытка получить кадр для индекса NaN вне диапазона при рендеринге FlatList - PullRequest
0 голосов
/ 14 июля 2020

Я пытался разработать простое приложение для обоев с использованием API Pexel. Я использовал плоский список для рендеринга изображений и ax ios для выборки данных из API, но он продолжает давать мне следующую ошибку: «Неизменяемое нарушение: попытка получить кадр для индекса вне диапазона NaN»

Это мой код

import {
  StyleSheet,
  Text,
  View,
  ActivityIndicator,
  FlatList,
  Dimensions,
  Image,
  Animated,
  TouchableWithoutFeedback,
  TouchableOpacity,
  CameraRoll,
  Share,
} from 'react-native';

import * as Permissions from 'expo-permissions';
import Lightbox from 'react-native-lightbox';
import { Ionicons } from '@expo/vector-icons'; 

import axios from 'axios';

const { height, width } = Dimensions.get('window');
export default class HomeWall extends React.Component {
  constructor() {
    super();
    this.state = {
      isLoading: true,
      images: [],
      scale: new Animated.Value(1),
      isImageFocused: false
    };

    this.scale = {
      transform: [{ scale: this.state.scale }]
    };

    this.actionBarY = this.state.scale.interpolate({
      inputRange: [0.9, 1],
      outputRange: [0, -80]
    });
    this.borderRadius = this.state.scale.interpolate({
      inputRange: [0.9, 1],
      outputRange: [30, 0]
    });
  }

  loadWallpapers = () => {
    axios
      .get(
        'https://api.pexels.com/v1/curated?per_page=1',  {
          headers: {
            'Authorization': 'My_Key'
          }
        })
      .then(
        function(response) {
          console.log(response.data);
          this.setState({ images: response.data, isLoading: false });
        }.bind(this)
      )
      .catch(function(error) {
        console.log(error);
      })
      .finally(function() {
        console.log('request completed');
      });
  };

  componentDidMount() {
    this.loadWallpapers();
  }

  saveToCameraRoll = async image => {
    let cameraPermissions = await Permissions.getAsync(Permissions.CAMERA_ROLL);
    if (cameraPermissions.status !== 'granted') {
      cameraPermissions = await Permissions.askAsync(Permissions.CAMERA_ROLL);
    }

    if (cameraPermissions.status === 'granted') {
      FileSystem.downloadAsync(
        image.urls.regular,
        FileSystem.documentDirectory + image.id + '.jpg'
      )
        .then(({ uri }) => {
          CameraRoll.saveToCameraRoll(uri);
          alert('Saved to photos');
        })
        .catch(error => {
          console.log(error);
        });
    } else {
      alert('Requires cameral roll permission');
    }
  };
 
  renderItem = ({ item }) => {
    return (
      <View style={{ flex: 1 }}>
        <View
          style={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: 'black',
            alignItems: 'center',
            justifyContent: 'center'
          }}
        >
          <ActivityIndicator size="large" color="grey" />
        </View>
    <Lightbox 
    activeProps={activeProps}
    renderHeader={close => (
      <View>
      <TouchableOpacity onPress={close}>
        <Ionicons style={styles.closeButton} name="md-close" size={33} color="white" />
      </TouchableOpacity>
      </View>

    )}>
        <View   style={{flex:1/3, aspectRatio:0.6}}>        
                <Image style={{flex: 1, borderRadius: 10, borderColor:'black', borderWidth:2}} resizeMode='cover'  source={{ uri: item.url }}>
                </Image>
        </View>
        </Lightbox>   
      </View>
    );
  };
  render() {
    return this.state.isLoading ? (
      
      <View
        style={{
          flex: 1,
          backgroundColor: 'black',
          alignItems: 'center',
          justifyContent: 'center'
        }}
      >
        <ActivityIndicator size="large" color="grey" />
      </View>
    ) : (
      <View style={{ flex: 1, backgroundColor: 'black' }}>
        <FlatList
          scrollEnabled={!this.state.isImageFocused}
          numColumns={2}
          data={this.state.images}
          renderItem={this.renderItem}
          keyExtractor={item => item.id}
        />
      </View>
    );
  }
}

const activeProps = { resizeMode: 'contain', flex: 1, height }; 

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center'
  },
  closeButton: {
    marginLeft: 23,
    marginTop: 23,
    alignSelf: 'flex-start',
  },
});

это пример формата введите описание изображения здесь данные api, полученные из pexel

  "id": 2014422,
  "width": 3024,
  "height": 3024,
  "url": "https://www.pexels.com/photo/brown-rocks-during-golden-hour-2014422/",
  "photographer": "Joey Farina",
  "photographer_url": "https://www.pexels.com/@joey",
  "photographer_id": 680589,
  "src": {
    "original": "https://images.pexels.com/photos/2014422/pexels-photo-2014422.jpeg",
    "large2x": "https://images.pexels.com/photos/2014422/pexels-photo-2014422.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
    "large": "https://images.pexels.com/photos/2014422/pexels-photo-2014422.jpeg?auto=compress&cs=tinysrgb&h=650&w=940",
    "medium": "https://images.pexels.com/photos/2014422/pexels-photo-2014422.jpeg?auto=compress&cs=tinysrgb&h=350",
    "small": "https://images.pexels.com/photos/2014422/pexels-photo-2014422.jpeg?auto=compress&cs=tinysrgb&h=130",
    "portrait": "https://images.pexels.com/photos/2014422/pexels-photo-2014422.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800",
    "landscape": "https://images.pexels.com/photos/2014422/pexels-photo-2014422.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=627&w=1200",
    "tiny": "https://images.pexels.com/photos/2014422/pexels-photo-2014422.jpeg?auto=compress&cs=tinysrgb&dpr=1&fit=crop&h=200&w=280"
  }
}
...