warum erscheint der button karte in homescreen : " import React, { useEffect, useState,…
- User
warum erscheint der button karte in homescreen :
"
import React, { useEffect, useState, useCallback } from 'react'; import { View, ActivityIndicator, Text, StyleSheet, Dimensions, Image, StatusBar, Platform } from 'react-native'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; import { useQuery } from '@apollo/client'; import { listStudiosByType } from './queries'; import LogoHeader from '../../components/LogoHeader'; import Searchbar from '../../components/Searchbar'; import StudioFilter from '../../components/StudioFilter'; import defaultStyles from '../../theme/Styles'; import colors from '../../theme/colors'; import ListingsMap from '../../components/Maps/ListingsMap'; import ListingBottomSheet from '../../components/ListingBottomSheet';
const QUEUE_DURATION = 5000; // 5 Sekunden Warteschlange
const HomeScreen = () => { const [showQueue, setShowQueue] = useState(true); const [queueProgress, setQueueProgress] = useState(0); const [studioType, setStudioType] = useState(''); const [priceRange, setPriceRange] = useState({ minPrice: 0, maxPrice: 300 }); const [isMapVisible, setIsMapVisible] = useState(false); const insets = useSafeAreaInsets(); const { height: screenHeight } = Dimensions.get('window');
const { data, loading, error, refetch } = useQuery(listStudiosByType, { variables: { studioType: studioType }, });
const simulateQueue = useCallback(() => { let progress = 0; const interval = setInterval(() => { progress += 30; setQueueProgress(progress); if (progress >= 100) { clearInterval(interval); setShowQueue(false); } }, QUEUE_DURATION / 15);
return () => clearInterval(interval);}, []);
useEffect(() => { const queueTimer = setTimeout(() => { setShowQueue(false); }, QUEUE_DURATION);
const cleanupQueue = simulateQueue(); return () => { clearTimeout(queueTimer); cleanupQueue(); };}, [simulateQueue]);
useEffect(() => { refetch(); }, [studioType, priceRange, refetch]);
const handleFilterChange = (type: string) => { setStudioType(type); };
const handlePriceFilterApply = (newPriceRange) => { setPriceRange(newPriceRange); };
const renderQueue = () => ( {//} <Image source={require('../../assets/images/StuWeiss-Ladebildschirm.png')} // Pfad zu Ihrem Bild style={{ width: 400, height: 100 }} // Passen Sie die Größe des Bildes an /> );
const showMap = () => { setIsMapVisible(true); };
const showList = () => { setIsMapVisible(false); }; const renderContent = () => ( <>
</View> <View style={styles.separator} /> <View style={styles.stackContainer}> <View style={styles.bottomSheetContainer}> <ListingsMap listingStudios={data?.listStudios?.items || []} showList={showList}/> <ListingBottomSheet studio={data?.listStudios?.items || []} refetch={refetch} loading={loading} showMap={showMap} showList={showList} isMapVisible={isMapVisible} /> </> );
if (error) { return ( {error.message} ); }
return ( <View style={[defaultStyles.container, { paddingTop: Platform.OS === 'android' ? StatusBar.currentHeight : insets.top }]}> {/* StatusBar Handling für Android */} {Platform.OS === 'android' && } {showQueue ? renderQueue() : null} <View style={[styles.contentContainer, showQueue && styles.hidden]}> {renderContent()} ); };
const styles = StyleSheet.create({ container: { height: '100%', backgroundColor: 'rgb(255, 255, 255)', }, queueContainer: { ...StyleSheet.absoluteFillObject, justifyContent: 'center', alignItems: 'center', backgroundColor: 'white', zIndex: 10, }, queueText: { marginTop: 10, fontSize: 16, color: colors.Grey, }, contentContainer: { flex: 1, marginBottom: 95
}, hidden: { opacity: 0, }, errorContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'white', }, errorText: { fontSize: 16, color: 'red', textAlign: 'center', marginTop: 20, }, buttons: { padding: 8, paddingHorizontal: 22, justifyContent: 'space-between', }, separator: { height: 1, backgroundColor: 'lightgrey', }, stackContainer: { flex: 1, }, bottomSheetContainer: { ...StyleSheet.absoluteFillObject, }, });
export default HomeScreen; "
aber in Searchresultscreen erscheint er kurz und verschwindet sofort :
"import React, { useEffect, useState } from 'react'; import { View, ActivityIndicator, Text, StyleSheet } from 'react-native'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; import { useQuery } from '@apollo/client'; import LogoHeader from '../../components/LogoHeader'; import Searchbar from '../../components/Searchbar'; import StudioFilter from '../../components/StudioFilter'; import defaultStyles from '../../theme/Styles'; import Seperator from '../../components/Seperator/Seperator'; import colors from '../../theme/colors'; import ListingsMap from '../../components/Maps/ListingsMap'; import ListingBottomSheet from '../../components/ListingBottomSheet'; import { listStudiosByBoundingBox, listStudiosByBoundingBoxAndTypeAndPrice } from './queries'; import { RouteProp, useNavigation } from '@react-navigation/native'; import { HomeStackNavigatorParamList } from '../../types/navigation';
type SearchResultRouteProp = RouteProp<HomeStackNavigatorParamList, 'SearchResultScreen'>;
type SearchResultProps = { route: SearchResultRouteProp; };
const calculateBoundingBox = (lat, lng, latDelta, lonDelta) => { const minLat = lat - latDelta / 2; const maxLat = lat + latDelta / 2; const minLon = lng - lonDelta / 2; const maxLon = lng + lonDelta / 2;
return { minLat, maxLat, minLon, maxLon, }; };
const SearchResultScreen: React.FC = ({ route }) => { const insets = useSafeAreaInsets(); const navigation = useNavigation(); const [studioType, setStudioType] = useState(''); const [priceRange, setPriceRange] = useState([0, 800]); const [location, setLocation] = useState({ latitude: 52.52000659999999, longitude: 13.404954 }); const [isMapVisible, setIsMapVisible] = useState(false);
const { radius, latitude, longitude, selectedGuest, selectedMinimumHours, adress } = route.params;
const boundingBox = calculateBoundingBox(latitude, longitude, radius / 100, radius / 100);
const { data, loading, error, refetch } = useQuery( listStudiosByBoundingBoxAndTypeAndPrice, { variables: { minLat: boundingBox.minLat, maxLat: boundingBox.maxLat, minLon: boundingBox.minLon, maxLon: boundingBox.maxLon, pricePerHourMin: priceRange[0], pricePerHourMax: priceRange[1], studioType: studioType, }, skip: !latitude || !longitude, } );
useEffect(() => { if (latitude && longitude) { refetch(); } }, [latitude, longitude, radius, selectedGuest, selectedMinimumHours, studioType, priceRange]);
useEffect(() => { const unsubscribe = navigation.addListener('focus', () => { refetch(); });
return unsubscribe;}, [navigation, refetch]);
const handleRegionChangeComplete = (region) => { const newBoundingBox = calculateBoundingBox(region.latitude, region.longitude, region.latitudeDelta, region.longitudeDelta); setLocation({ latitude: region.latitude, longitude: region.longitude }); refetch({ minLat: newBoundingBox.minLat, maxLat: newBoundingBox.maxLat, minLon: newBoundingBox.minLon, maxLon: newBoundingBox.maxLon, pricePerHourMin: priceRange[0], pricePerHourMax: priceRange[1], studioType: studioType,
});};
const handleFilterApply = (selectedPriceRange) => { setPriceRange([selectedPriceRange.minPrice, selectedPriceRange.maxPrice]); refetch({ minLat: boundingBox.minLat, maxLat: boundingBox.maxLat, minLon: boundingBox.minLon, maxLon: boundingBox.maxLon, pricePerHourMin: selectedPriceRange.minPrice, pricePerHourMax: selectedPriceRange.maxPrice, ...(studioType !== '' && { studioType }), }); };
if (loading) { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> ); }
if (error) { console.error('GraphQL Error:', error); return {error.message}; }
const studios = data?.listStudios?.items || []; const showMap = () => { setIsMapVisible(true); };
const showList = () => { setIsMapVisible(false); };
return ( <View style={[defaultStyles.container, { paddingTop: insets.top }]}> {/**<Searchbar filterOn={true} inputText={adress} priceRange={{ minPrice: priceRange[0], maxPrice: priceRange[1] }} onFilterApply={handleFilterApply} /> */} <Searchbar inputText={adress} priceRange={{ minPrice: priceRange[0], maxPrice: priceRange[1] }} onFilterApply={handleFilterApply} filterOn={true} />
<View style={styles.stackContainer}> <View style={styles.bottomSheetContainer}> <ListingsMap showList={showList} radius={radius} initialLatitude={latitude} initialLongitude={longitude} listingStudios={studios} onRegionChangeComplete={handleRegionChangeComplete} /> <ListingBottomSheet studio={studios} refetch={refetch} loading={loading} showMap={showMap} showList={showList} isMapVisible={isMapVisible} /> </View> </View> </View>); };
const styles = StyleSheet.create({ container: { height: '100%', backgroundColor: 'rgb(255, 255, 255)', }, buttons: { padding: 8, paddingHorizontal: 22, justifyContent: 'space-between',
},
separator: { height: 1, backgroundColor: 'lightgrey', }, stackContainer: { flex: 1, }, bottomSheetContainer: { ...StyleSheet.absoluteFillObject, }, });
export default SearchResultScreen; "
hier ist der karte button :
"import { View, Text, FlatList, StyleSheet, TouchableOpacity, Dimensions, Platform } from 'react-native'; import React, { useCallback, useMemo, useState } from 'react'; import BottomSheet, { BottomSheetFlatList } from "@gorhom/bottom-sheet"; import StudioFeedItem from '../StudioFeedItem'; import Ionicons from 'react-native-vector-icons/Ionicons'; import colors from '../../theme/colors'; import { useBottomTabBarHeight } from '@react-navigation/bottom-tabs'; import defaultStyles from '../../theme/Styles'; import { FlashList } from '@shopify/flash-list';
interface IListingBottomSheet { studio : { id: string; StudioName: string; pricePerHour: number; latitude: number; longitude: number; }[]; refetch: () => void; loading: boolean; showMap: () => void; showList: () => void; isMapVisible: boolean;
}
const ListingBottomSheet = ({ studio, refetch, loading, showMap, showList, isMapVisible }: IListingBottomSheet) => { const bottomSheetRef = React.useRef(null); const [indicatorStyle, setIndicatorStyle] = useState({ backgroundColor: 'black' }); const [isMapView, setIsMapView] = useState(false);
const { height: screenHeight } = Dimensions.get('window'); const snapPoints = useMemo(() => ['1%', '100%'], []);/* const snapPoints = React.useMemo(() => [ screenHeight * 1, screenHeight * 1 ], [screenHeight]); */
const handleSheetChanges = useCallback((index: number) => { if (index === 1) { setIndicatorStyle({ backgroundColor: 'transparent' }); } else { setIndicatorStyle({ backgroundColor: 'transparent' }); } }, []);// const ListComponent = Platform.select({ // android: FlashList, // ios: FlashList, // }); const renderItem = useCallback(({ item }) => ( ), []);
const keyExtractor = useCallback((item) => item.id, []);
return ( <BottomSheet snapPoints={snapPoints} ref={bottomSheetRef} //index={1} index={isMapVisible ? 0 : 1} enablePanDownToClose={false} // Fügen Sie diese Zeile hinzu enableContentPanningGesture={false} backgroundStyle={{ borderRadius: 0 }} style={isMapVisible ? { marginTop: 10 } : {}} //backgroundStyle={{ backgroundColor: 'transparent' }} // Hintergrund transparent machen handleStyle={{ display: 'none' }} // Handle ausblenden handleIndicatorStyle={{ display: 'none' }} // Handleindikator ausblenden onChange={handleSheetChanges} > <FlashList data={studio} showsVerticalScrollIndicator={false} renderItem={renderItem} //renderItem={({ item }) => <StudioFeedItem studioItem={item} />} onRefresh={() => refetch()} refreshing={loading} estimatedItemSize={200} keyExtractor={keyExtractor} /> {!isMapVisible && ( <View style={styles.absoulutBtn}> <TouchableOpacity onPress={showMap} style={styles.btn}> <Text style={[defaultStyles.regularSmall, { color: colors.white }]}> Karte </Text> <Ionicons name="map" size={20} color="#ffffff" /> </TouchableOpacity> </View> )} </BottomSheet> );};
const styles = StyleSheet.create({ absoulutBtn: { position: 'absolute', bottom: 25, width: '100%', alignItems: 'center', borderColor: 'black', }, btn: { backgroundColor: colors.DarkGrey, borderColor: colors.DarkGrey, paddingVertical: 13, paddingHorizontal: 17, borderRadius: 30, borderWidth: 1, gap: 10, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', } });
export default ListingBottomSheet;"
- Assistant
Der Grund, warum der "Karte"-Button im
HomeScreensichtbar bleibt, während er imSearchResultScreennur kurz erscheint und dann verschwindet, liegt höchstwahrscheinlich an der Art und Weise, wie der ZustandisMapVisibleimSearchResultScreenverwaltet wird. Hier sind einige mögliche Ursachen und Lösungsvorschläge:Ursache
-
Zustandsverwaltung (
isMapVisible):- Im
HomeScreenbleibt der ZustandisMapVisiblekonsistent, sodass der Button sichtbar bleibt, bis der Benutzer ihn explizit ändert. - Im
SearchResultScreenkönnte der ZustandisMapVisiblemöglicherweise ungewollt geändert werden, beispielsweise durch eine erneute Abfrage (refetch) oder durch ein anderes useEffect, das den Zustand beeinflusst.
- Im
-
BottomSheet Konfiguration:
- Die
snapPointsund derindeximBottomSheetbestimmen, wie das Sheet initial und bei Änderungen angezeigt wird. Unterschiedliche Konfigurationen zwischenHomeScreenundSearchResultScreenkönnten das Verhalten beeinflussen.
- Die
-
Re-Render und Zustand:
- Im
SearchResultScreenwirdrefetchhäufig verwendet, was zu wiederholten Re-Renders führen könnte. Diese Re-Renders könnten den ZustandisMapVisiblezurücksetzen oder verändern, wenn er nicht richtig verwaltet wird.
- Im
Lösungsvorschläge
-
Überprüfung und Debugging des Zustands
isMapVisible:- Fügen Sie
console.log-Anweisungen hinzu, um zu überprüfen, wann und wie sichisMapVisibleimSearchResultScreenändert. - Stellen Sie sicher, dass
isMapVisiblenur durch dieshowMap- undshowList-Funktionen geändert wird und nicht unbeabsichtigt durch andere Mechanismen.
useEffect(() => { console.log("isMapVisible:", isMapVisible); }, [isMapVisible]); - Fügen Sie
-
Anpassung der
snapPointsundindex:- Überprüfen Sie, ob die
snapPointsimListingBottomSheetimSearchResultScreenkorrekt gesetzt sind. Möglicherweise möchten Sie andere Werte ausprobieren, um sicherzustellen, dass der Button sichtbar bleibt. - Stellen Sie sicher, dass der
indexkorrekt gesetzt wird und nicht ungewollt den Zustand ändert.
const snapPoints = useMemo(() => ['25%', '100%'], []); - Überprüfen Sie, ob die
-
Vermeiden von unnötigen Re-Renders:
- Minimieren Sie die Anzahl der Re-Renders im
SearchResultScreen, indem Sie Abhängigkeiten in denuseEffect-Hooks sorgfältig verwalten. - Verwenden Sie
useCallbackunduseMemofür Funktionen und Werte, die als Props weitergegeben werden, um unnötige Re-Renders zu vermeiden.
- Minimieren Sie die Anzahl der Re-Renders im
-
Zustandsmanagement in
ListingBottomSheet:- Stellen Sie sicher, dass die
ListingBottomSheet-Komponente den ZustandisMapVisiblenur basierend auf den übergebenen Props ändert und nicht selbst weitere Zustandsänderungen durchführt.
const ListingBottomSheet = ({ studio, refetch, loading, showMap, showList, isMapVisible }) => { // ... return ( <BottomSheet // ... > {/* Listen und Inhalte */} {!isMapVisible && ( <View style={styles.absoulutBtn}> <TouchableOpacity onPress={showMap} style={styles.btn}> <Text style={[defaultStyles.regularSmall, { color: colors.white }]}> Karte </Text> <Ionicons name="map" size={20} color="#ffffff" /> </TouchableOpacity> </View> )} </BottomSheet> ); }; - Stellen Sie sicher, dass die
-
Synchronisation der Zustände zwischen Komponenten:
- Stellen Sie sicher, dass der Zustand
isMapVisiblekonsistent zwischenSearchResultScreenundListingBottomSheetsynchronisiert bleibt. Ein inkonsistenter Zustand kann dazu führen, dass der Button ungewollt verschwindet.
- Stellen Sie sicher, dass der Zustand
Beispielhafte Anpassung
Hier ist eine angepasste Version des
SearchResultScreen, die sicherstellt, dassisMapVisiblekorrekt verwaltet wird:const SearchResultScreen: React.FC<SearchResultProps> = ({ route }) => { // ... andere Zustände und Hooks const [isMapVisible, setIsMapVisible] = useState(false); // Debugging: Zustand überwachen useEffect(() => { console.log("SearchResultScreen - isMapVisible:", isMapVisible); }, [isMapVisible]); // Refetch nur bei bestimmten Änderungen useEffect(() => { if (latitude && longitude) { refetch(); } }, [latitude, longitude, radius, selectedGuest, selectedMinimumHours, studioType, priceRange, refetch]); // Navigation Listener fixieren useEffect(() => { const unsubscribe = navigation.addListener('focus', () => { refetch(); }); return unsubscribe; }, [navigation, refetch]); // ... andere Funktionen return ( <View style={[defaultStyles.container, { paddingTop: insets.top }]}> <LogoHeader /> <Searchbar inputText={adress} priceRange={{ minPrice: priceRange[0], maxPrice: priceRange[1] }} onFilterApply={handleFilterApply} filterOn={true} /> <View style={styles.buttons}> <StudioFilter studioType={studioType} setStudioType={setStudioType} /> </View> <View style={styles.separator}></View> <View style={styles.stackContainer}> <View style={styles.bottomSheetContainer}> <ListingsMap showList={showList} radius={radius} initialLatitude={latitude} initialLongitude={longitude} listingStudios={studios} onRegionChangeComplete={handleRegionChangeComplete} /> <ListingBottomSheet studio={studios} refetch={refetch} loading={loading} showMap={showMap} showList={showList} isMapVisible={isMapVisible} /> </View> </View> </View> ); };Weitere Tipps
- Logging und Debugging: Verwenden Sie umfangreiches Logging, um den Zustand und die Render-Zyklen Ihrer Komponenten zu überwachen.
- Komponente isolieren: Testen Sie die
ListingBottomSheet-Komponente isoliert in beiden Screens, um sicherzustellen, dass sie unabhängig korrekt funktioniert. - React Navigation: Stellen Sie sicher, dass die Navigation zwischen den Screens nicht unbeabsichtigte Seiteneffekte auf den Zustand hat.
Durch eine sorgfältige Überprüfung und Anpassung der Zustandsverwaltung sowie der
BottomSheet-Konfiguration sollte der "Karte"-Button imSearchResultScreenstabil und dauerhaft sichtbar bleiben, wie es imHomeScreender Fall ist. -