开发者问题收集

TypeError:未定义不是一个对象(评估“appState.remove”)

2021-10-12
3148

在此处输入图片描述 我很难处理这个错误,因为以前一切都运行正常,但现在它却说它已被弃用。有人能帮我解决错误吗?因为它根本不起作用,我尝试了 App State 文档中的新代码,但仍然出现相同的错误 TypeError:undefined 不是对象(评估“appState.remove”)

这是我的代码:

constructor(props) {
    super(props);
    this.state = {
      region: null,
      status: undefined,
      appState: AppState?.currentState,
      modalVisible: true,
      isLoading: true,
    };
    this._getLocationAsync();
  }

  componentDidMount() {
    AppState.removeEventListener("change", this.handleAppStateChange);
  }
  handleAppStateChange = (nextAppState) => {
    if (
      this.state.appState.match(/inactive|background/) &&
      nextAppState === "active"
    ) {
      this._getLocationAsync();
    }
    this.setState({ appState: nextAppState });
  };

  componentWillUnmount() {
    AppState.addEventListener("change", this.handleAppStateChange);

    this._getLocationAsync();
  }
  _getLocationAsync = async () => {
    let { status } = await Location.requestPermissionsAsync();
    let location = await Location.getCurrentPositionAsync({
      enableHighAccuracy: false,
      timeout: 10000,
      maximumAge: 0,
    });

    let region = {
      latitude: location.coords.latitude,
      longitude: location.coords.longitude,
      latitudeDelta: 0.0045,
      longitudeDelta: 0.0045,
    };
    this.props.callback({
      latitude: region.latitude,
      longitude: region.longitude,
    });
    this.setState({ region: region, status: status });
  };
2个回答
//listen to AppState change in componentDidMount
componentDidMount() {
    this.subscriptionToAppState = AppState.addEventListener("change",  this.handleAppStateChange);
}

//stop listen 
componentWillUnmount() {
    //if your react native version 0.65 or more use this
    this.subscriptionToAppState.remove();
    //if your react native version min than v 0.65 use the deprecated methode like this 
    this.subscriptionToAppState.removeEventListener("change", this.handleAppStateChange);
}
Ahmed Gaber
2021-10-12

如果我们按照下面的方式实现,我们就可以避免这个错误。

import {
  AppState
} from 'react-native';

const appState = useRef(AppState.currentState);

 useEffect(() => {
        AppState.addEventListener('change', handleAppStateChange);
        return () => {
            console.log('unmount');
          AppState.removeEventListener('change', handleAppStateChange);
        };
      }, []);


    const handleAppStateChange = (nextAppState) => {
        console.log('App State: ' + nextAppState);
        if (appState.current != nextAppState) {
          if (appState.current.match(/inactive|background/) 
                && nextAppState === 'active') {
            console.log(
              'App State: ' +
              'App has come to the foreground!'
            );
          }
          appState.current = nextAppState;
        }
      };
JAK
2022-10-02