尝试制作制作者。重新渲染太多。 React 限制渲染数量以防止无限循环

问题描述 投票:0回答:1

我正在开发 EXPO 的 React Native 应用程序。 我刚刚遇到以下错误。

Too many re-renders. React limits the number of renders to prevent an infinite loop.

我会得到 jissaitoretatoomou 吗? [{“纬度”:35.52400475291494,“经度”:139.4506602713825,“user_id”:0}] 并为每个元素渲染 s 的纬度和经度。”

import React, { useState, useEffect } from "react";
import { View, Text, ScrollView, StyleSheet, TextInput, Button ,Switch,Dimensions,Image} from "react-native";
import { useNavigation } from '@react-navigation/native'; // useNavigationを追加
import MapView, { Marker ,Polyline} from 'react-native-maps';
import {requestLocationPermission,getCurrentLocation,writeMyLocationData} from '../../sockets/googlemap'
import {findPlace,fetchRoute} from '../../sockets/googleroute'
import { ref,onChildAdded} from "firebase/database";
import { database } from '../../firebaseConfig'; // Firebaseのデータベースを正しくインポートする必要があります



const Main = () => {
        const [otherRiders, setOtherRiders] = useState([]);
 
    const dbref = ref(database); //取得したいデータのパスを指定
    onChildAdded(dbref, function (snapshot) {
        let data = snapshot.val();
        setOtherRiders(data)
        console.log("jissaitoretatoomou?",data);
});
    console.log("kakunin",otherRiders)
    const [routeInfo, setRouteInfo] = useState({ origin: "", destination: "" });
    const navigation = useNavigation(); // useNavigationフックを使用してnavigationオブジェクトを取得
    const [myCurrentLocation,setMyCurrentLocation] = useState({
        latitude: 0,
        longitude: 0,
    })
    const [myDestination,setMyDestination] = useState({
        latitude: 0,
        longitude: 0,
    })
    const [myOrigin,setMyOrigin] = useState({
        latitude: 0,
        longitude: 0,
    })
    // DB を取得している
    
    const [isMapReady, setIsMapReady] = useState(false);
    const [isEnabled, setIsEnabled] = useState(false);
    const toggleSwitch = () => setIsEnabled(previousState => !previousState);
    const iconImage = require('../../assets/kurumi.jpg');
    const myDestinationIcon = require('../../assets/flag.png');

    // requestLocationPermission();
    useEffect(() => {
        requestLocationPermission(setMyCurrentLocation,myCurrentLocation,setIsMapReady);
        
    });

    return (
        isMapReady ? ( // マップが準備完了したら表示
        <ScrollView  style={styles.Wrapper}>
            
                <View style={styles.mapContainer}>
                    <MapView style={styles.map}
                        initialRegion={{
                            latitude: myCurrentLocation.latitude,
                            longitude: myCurrentLocation.longitude,
                            latitudeDelta: 0.0922,
                            longitudeDelta: 0.0421,
                        }}
                    >
                        <Marker
                            coordinate={{
                                latitude: myCurrentLocation.latitude,
                                longitude: myCurrentLocation.longitude,
                            }}
                        >
                            <Image style={styles.icon} source={iconImage} />
                        </Marker>
                        <Marker
                            coordinate={{
                                latitude: myDestination.latitude,
                                longitude: myDestination.longitude,
                            }}
                        >
                            <Image style={styles.icon} source={myDestinationIcon} />
                        </Marker>
                            <Polyline
                            coordinates={[
                                { latitude: myOrigin.latitude, longitude: myOrigin.longitude },
                                { latitude: myDestination.latitude, longitude: myDestination.longitude },
                            ]}
                            strokeColor="#FF0000" // 線の色
                            strokeWidth={2} // 線の太さ
                        />


                    </MapView>
                </View>                
            <View>
                <Text style={styles.direction}>出発地</Text>
                <TextInput
                    placeholder={'出発地を入力してください'}
                    value={routeInfo.origin}
                    autoCapitalize="none"
                    onChangeText={text => setRouteInfo({ ...routeInfo, origin: text })} // オブジェクトをスプレッドして、originプロパティのみを更新
                    style={styles.imputBox}
                />
            </View>
            <View>
                <Text style={styles.direction}>目的地</Text>
                <TextInput
                    placeholder={'到着地を入力してください'}
                    value={routeInfo.destination}
                    autoCapitalize="none"
                    onChangeText={text => setRouteInfo({ ...routeInfo, destination: text })} // オブジェクトをスプレッドして、destinationプロパティのみを更新
                    style={styles.imputBox}
                />
            </View>
            <View>
                <Button
                    title="ルートを検索する"
                    onPress={() => fetchRoute(setMyOrigin,setMyDestination,routeInfo)}
                />
            </View>
            <View>
                <Text style={styles.infomation}>位置情報共有をONにする</Text>
                <Switch
                    trackColor={{false: '#767577', true: '#81b0ff'}}
                    thumbColor={isEnabled ? '#f5dd4b' : '#f4f3f4'}
                    ios_backgroundColor="#3e3e3e"
                    onValueChange={toggleSwitch}
                    value={isEnabled}
                />
            </View>
            <View>
                <Button
                    title="戻る"
                    onPress={() => navigation.navigate('Top')}
                />
            </View>
        </ScrollView>
        ):<ScrollView style={styles.waitScrollViewContent}><View style={styles.center}><Text style={styles.infomation}>少々お待ちください。。。</Text></View></ScrollView>
    )
}

export default Main;

const { height } = Dimensions.get("window");
const mapHeight = height * 0.5; // 画面の半分の高さ
const styles = StyleSheet.create({
    Wrapper:{
        flex: 1, // 画面の半分のサイズに設定
    },
    direction: {
        fontSize: 12,
        padding:10
    },
    infomation: {
        fontSize: 12,
        padding:10
    },
    subTitle: {
        fontSize: 14,
        textAlign: "center",
        padding:5
    },
    mapContainer: {
        height: mapHeight,
        justifyContent: 'center',
        alignItems: 'center',
    },
    map: {
        ...StyleSheet.absoluteFillObject,
    },
    markerContainer: {
        backgroundColor: 'blue',
        padding: 5,
        borderRadius: 5,
    },
    markerText: {
        color: 'white',
        fontWeight: 'bold',
    },
    imputWrapper: {
        alignItems: "center", // 横方向に中央揃え
        padding: 20
    },
    imputContainer:{
        width:'100%',
        marginBottom:10
    },
    imputBox: {
        height: 40,
        borderWidth: 1,
    },
    icon: {
      width: 28,
      height: 28,
    },
    waitScrollViewContent: {
    flex: 1,
    width:'100%',
  },
    center: {
    flex: 1,
        justifyContent: 'center',
        alignItems: 'center',

    },
});

我尝试在useEffect之间写onChildAdded 我尝试将回调写入 setIntervel

javascript
1个回答
0
投票

我认为你在

useEffect
中调用api而不依赖,这将在每次渲染时执行。您需要添加依赖项。

useEffect(() => {
  requestLocationPermission(setMyCurrentLocation,myCurrentLocation,setIsMapReady);        
}, []);
// empty dependency will only executed once

如果需要保留更新位置,请在

setInterval
中添加
useEffect

useEffect(() => {
  const interval = setInterval(() => {
    requestLocationPermission(setMyCurrentLocation,myCurrentLocation,setIsMapReady);      
  }, 5000);
  return () => clearInterval(interval);
}, []);
© www.soinside.com 2019 - 2024. All rights reserved.