Приложение React Native My expo продолжает запрашивать данные из api даже после загрузки данных

#react-native

Вопрос:

Мое приложение expo продолжает запрашивать данные из API даже после того, как оно загрузило данные, даже после того, как я покинул текущий экран, он продолжает получать их. …………………………………………………………………………………………………………………………………………………………………………………………………

 
import styles from '../HomeScreen/style';
import React, { useEffect, useState } from "react";

import {
Dimensions,
  FlatList,
  SafeAreaView,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View,
  Image,
  Animated,
  Button,
} from 'react-native';

import Icon from 'react-native-vector-icons/MaterialIcons';
import COLORS from '../HomeScreen/colors';
import hotels from '../HomeScreen/hotels';
//import hotels from '../HomeScreen/hotels';
const {width} = Dimensions.get('screen');
const cardWidth = width / 1.8;


const CityScreen = ({navigation}) => {


  const categories = ['All', 'Popular', 'Top Rated','low Budget'];
  const [selectedCategoryIndex, setSelectedCategoryIndex] = React.useState(0);
  const [activeCardIndex, setActiveCardIndex] = React.useState(0);
  const scrollX = React.useRef(new Animated.Value(0)).current;

 

  const [dataa,setData] = useState("");
  const [isLoading,setLoading] = useState(true);

  useEffect(()=>{
    fetch('https://egytourism.000webhostapp.com/fetch_city.php')   
    .then((response) => response.json())  
      .then((json) => {     setData(json)   })
      .then(setLoading(false))
      .then(console.log("0"))   
       .catch((error) => {      console.error(error);    })
  

  ,[]})
 
  
  const Card = ({hotel, index}) => {
    const id = hotel.id;
    const inputRange = [
      (index - 1) * cardWidth,
      index * cardWidth,
      (index   1) * cardWidth,
    ];
    const opacity = scrollX.interpolate({
      inputRange,
      outputRange: [0.7, 0, 0.7],
    });
    const scale = scrollX.interpolate({
      inputRange,
      outputRange: [0.8, 1, 0.8],
    });
    return (
      <TouchableOpacity
        disabled={activeCardIndex != index}
        activeOpacity={1}
        onPress={() => navigation.navigate('ChoiceScreen', id)}>
       

        <Animated.View style={{...styles.card, transform: [{scale}]}}>
          <Animated.View style={{...styles.cardOverLay, opacity}} />

          <Image  source={{uri:hotel.image }}  style={styles.cardImage} />
          <View style={styles.cardDetails}>
            <View
              style={{flexDirection: 'row', justifyContent: 'space-between'}}>
              <View>
                <Text style={{fontWeight: 'bold', fontSize: 17}}>
                  {hotel.name}
                </Text>
                <Text style={{color: COLORS.grey, fontSize: 12}}>
                  {hotel.location}
                </Text>
              </View>
              <Icon name="bookmark-border" size={26} color={COLORS.primary} />
            </View>
            <View
              style={{
                flexDirection: 'row',
                justifyContent: 'space-between',
                marginTop: 10,
              }}>
              <View style={{flexDirection: 'row'}}>
                <Icon name="star" size={15} color={COLORS.orange} />
                <Icon name="star" size={15} color={COLORS.orange} />
                <Icon name="star" size={15} color={COLORS.orange} />
                <Icon name="star" size={15} color={COLORS.orange} />
                <Icon name="star" size={15} color={COLORS.grey} />
              </View>
              <Text style={{fontSize: 10, color: COLORS.grey}}>365reviews</Text>
            </View>
          </View>
        </Animated.View>
      </TouchableOpacity>
    );
  };


  return (
    <SafeAreaView style={{flex: 1, backgroundColor: COLORS.white}}>
      <View style={styles.header}>


      
        <View style={{paddingBottom: 15}}>
                <View style={styles.headers}>
          <Icon
            name="arrow-back-ios"
            size={28}
            color={COLORS.dark}
            onPress={navigation.goBack}
          />
          <Icon name="bookmark-border" size={28} color={COLORS.white} />
        </View>
          <Text style={{fontSize: 30, fontWeight: 'bold'}}>
            Find your hotel
          </Text>
          <View style={{flexDirection: 'row'}}>
            <Text style={{fontSize: 30, fontWeight: 'bold'}}>in </Text>
            <Text
              style={{fontSize: 30, fontWeight: 'bold', color: COLORS.primary}}>
              Cities
            </Text>
          </View>
        </View>
        <Icon name="person-outline" size={38} color={COLORS.grey} />
      </View>
      <ScrollView showsVerticalScrollIndicator={false}>

        <View>
          <Animated.FlatList
            onMomentumScrollEnd={(e) => {
              setActiveCardIndex(
                Math.round(e.nativeEvent.contentOffset.x / cardWidth),
              );
            }}
            onScroll={Animated.event(
              [{nativeEvent: {contentOffset: {x: scrollX}}}],
              {useNativeDriver: true},
            )}
            horizontal
            data={dataa}
            contentContainerStyle={{
              paddingVertical: 30,
              paddingLeft: 20,
              paddingRight: cardWidth / 2 - 40,
            }}
            showsHorizontalScrollIndicator={false}
            renderItem={({item, index}) => <Card hotel={item} index={index} />}
            snapToInterval={cardWidth}
          />
        </View>
       
      </ScrollView>
    </SafeAreaView>
  );
};
export default CityScreen;

 

если вы посмотрите на сетевую область, то окажется, что она запрашивает более одного раза
[1]: https://i.stack.imgur.com/DYByf.png

Ответ №1:

Похоже, что в вашем вызове useEffect есть опечатка, которая может быть причиной.

 useEffect(() => {
  fetch('https://egytourism.000webhostapp.com/fetch_city.php')   
    .then((response) => response.json())  
    .then((json) => { setData(json) })
    .then(setLoading(false))
    .then(console.log("0"))   
    .catch((error) => { console.error(error) })
}, [])
 

useEffect должен принимать два параметра, первый из которых-функция, а второй-массив зависимостей. В вашем коде функция ,[] находится внутри вызова функции, поэтому у нее есть только один параметр.