如何解决无法在卸载的组件上执行 React 状态更新!每当我显示地图时总是显示这个

如何解决如何解决无法在卸载的组件上执行 React 状态更新!每当我显示地图时总是显示这个

我有两个组件的类。首先是 TrackRoute1.js,我从中通过服务器将公交车位置参数和用户当前位置参数传递给类 dispaly.js。但是在显示后,我不断收到内存泄漏,表明它无法对卸载的组件执行反应状态更新。我尝试了一切。但这无济于事。

TrackRoute1.js

import React,{ Component } from "react";
import {
  ActivityIndicator,FlatList,Text,View,TouchableHighlight,StyleSheet,} from "react-native";
import AnimatedRegion from "react-native-maps";
import display1 from "./display1";
import { LogBox } from "react-native";
import CustomHeader from "../CustomHeader";

LogBox.ignoreLogs(["Setting a timer"]);
import * as Location from 'expo-location';

export default class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      data: [],isLoading: true,userLat: 0,userLng: 0,routeCoordinates: [],distanceTravelled: 0,prevLatLng: {},coordinate: new AnimatedRegion({
        userLat: 0,latitudeDelta: 0,longitudeDelta: 0
      })
    };
  }

  componentDidMount() {
    this.interval = setInterval(() => this.getCoords(),1000);
    this._getLocationAsync();

  }

  async getCoords() {
    fetch("https://api.thingspeak.com/channels/1323137/Feeds.json?results=1")
      .then((response) => response.json())
      .then((json) => {
        console.log(json.Feeds,"API res");
        this.setState({ data: json.Feeds });
      })
      .catch((error) => console.error(error))
      .finally(() => {
        this.setState({ isLoading: false });
      });
  }
  _getLocationAsync = async () => {

 console.log("123")
    let { status } = await Location.requestForegroundPermissionsAsync();
    console.log(status)
    if (status !== 'granted') {
      console.log('Permission to access location was denied');
      return;
    }

    // Old method //

    let location = await Location.getCurrentPositionAsync({});
    console.log(location,"my location");
      this.setState({
  userLat: Number(location.coords.latitude),userLng: Number(location.coords.longitude)
      })
    console.log(this.state.userLng,"userLng111")


    // New Method //
    // this.location = await Location.watchPositionAsync(
    //   {
    //     enableHighAccuracy: true,//     distanceInterval: 1,//     timeInterval: 1000
    //   },//   newLocation => {
    //     let { coords } = newLocation;
    //     // console.log(coords);
    //     this.setState({
    //       userLat: Number(coords.latitude),//         userLng: Number(coords.longitude)
    //           })
    //   },//   error => console.log(error)
    // );
    // return this.location;


  };


  
  calcdistance = newLatLng => {
    const { prevLatLng } = this.state;
    return haversine(prevLatLng,newLatLng) || 0;
  };


  componentwillUnmount() {
    clearInterval(this.interval);
    navigator.geolocation.clearWatch(this.watchID);

  }

  render() {
    const { data,isLoading } = this.state;

    return (
      <View style={{ flex: 1,width: "100%" }}>
        <CustomHeader title="Track Route" navigation={this.props.navigation} />

        {isLoading ? (
          <ActivityIndicator />
        ) : (
          <FlatList
            data={data}
            keyExtractor={(id,index) => index.toString()}
            renderItem={({ item }) => (
              <display1
                value1={item.field1}
                value2={item.field2}
                value3={item.field3}
                value4={this.state.userLat}
                value5={this.state.userLng}

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

const styles = StyleSheet.create({
  appButtonText: {
    fontSize: 18,color: "#fff",fontWeight: "bold",alignSelf: "center",textTransform: "uppercase",},});

dispaly.js

    import React,{ Component } from "react";
    import {
      StyleSheet,TouchableOpacity,Platform,Dimensions,Image,} from "react-native";
    import * as Location from 'expo-location';
    
    import MapView,{
      PROVIDER_GOOGLE,Marker,polyline,AnimatedRegion,} from "react-native-maps";
    import AutoScrolling from "react-native-auto-scrolling";
    
    import { getPrecisedistance } from 'geolib';
    
    const { width,height } = Dimensions.get("window");
    export default class Map extends Component {
      // constructor(props) {
      //   super(props);
      //   this.state = {
      //   };
      // }
      constructor(props) {
        super(props);
    
        this.marker = null;
        this.timeout = null;

        this.state = {
          isMapReady: false,Time:0,dis: 0,hasLocationPermissions: false,locationResult: null,coordinate: new AnimatedRegion({
            latitude: parseFloat(this.props.value1),longitude: parseFloat(this.props.value2),latitudeDelta: 0.05,longitudeDelta: 0.04,}),};
      }
      async componentDidMount() {
         this.mounted = true;
   this.timeout = setTimeout(()=>{ var pdis = getPrecisedistance(
          {latitude:parseFloat(this.props.value1),longitude: parseFloat(this.props.value2)},{latitude: parseFloat(this.props.value4),longitude: parseFloat(this.props.value5)},);
        // console.log(
        //   `Precise distance\n\n${pdis} Meter\nor\n${pdis / 1000} KM`
        // );
       this.setState({dis:pdis,Time:Math.round( pdis/(this.props.value3*1000) )})},2000)
    
    
        this.setState({
          Time:this.state.Time.toFixed(2)
        })
      }
      
      componentwillUnmount = () =>{
    this.mounted = false;
    if (this.timeout) {
      clearTimeout(this.timeout)
    }
  }
    
      onMapLayout = () => {
        this.setState({ isMapReady: true });
      };
    
      render() {
    //     console.log( this.state.userLat,//  this.state.userLng,"myConsole")
        return (
          <View>
            {this.state.dis !== 0 ?
              <View style={{backgroundColor:"rgba(52,52,0.00006)"}}>
                <Text style={{ color: "green",marginTop: 10,marginBottom: 3,}}>Bus is {this.state.dis / 1000} km Away.</Text>
                
                  <AutoScrolling style={{ backgroundColor: "rgba(52,0.00006)",width: 400,padding: 10,marginBottom: 10,}} endPadding={50}>
              <Text style={ {
        color: "red",fontSize: 20,textAlign: "center",margin: 5,}}>Bus is Coming in {this.state.Time} Minutes</Text>
            </AutoScrolling>
    
    </View>
            :null  }
    
            <MapView
            initialRegion={{
              latitude: parseFloat(this.props.value1),latitudeDelta: 0.02,longitudeDelta: 0.01,}}
            onMapReady={this.onMapLayout}
            provider={PROVIDER_GOOGLE}
            loadingIndicatorColor="#e21d1d"
            ref={(map) => (this.map = map)}
            style={{
          width,height
            }}
            loadingEnabled={true}
          >
            {this.state.isMapReady && (
              <MapView.Marker
                key="AIzaSyB8k3Irk81q1k8pbj5tPM33KRWNdtROoOg"
                identifier="marker"
    
                coordinate={{
                  latitude: parseFloat(this.props.value1),}}
                  flat={false}
                  title="Route 1"
                  description = "Driver: Muhammad Murtaza"
    
              >
              <Image source={require("D:/React Native apps/Bus-Track1-main/assets/car-marker.png")} style={{ width: 60,height: 50 }}/>
    
    
              </MapView.Marker>
            )}
              <MapView.Marker
                key="AIzaSyArnXt8Xqydc3BF9Udt8JCkFuKqgPR_HM0"
                identifier="marker1"
                coordinate={{
                  latitude: parseFloat(this.props.value4),longitude: parseFloat(this.props.value5)
                }}
                            title="My Location"
    
              />
            
           <polyline
            coordinates={[
        
            
                {   latitude: parseFloat(this.props.value4),longitude: parseFloat(this.props.value5)
                },{ latitude: parseFloat(this.props.value1),longitude: parseFloat(this.props.value2)
                },]}
            strokeColor="red" 
            strokeColors={[
                '#238C23','red'
            ]}
            strokeWidth={5}
        />
            </MapView>
            </View>
        );
      }
    }

我有两个组件的类。首先是 TrackRoute1.js,我从中通过服务器将公交车位置参数和用户当前位置参数传递给类 dispaly.js。但是在显示后,我不断收到内存泄漏,表明它无法对未安装的组件执行反应状态更新。我尝试了一切。但这无济于事。

Output

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?