如何使用监视地理位置变化的地理位置组件?

How to use a geolocation component that watches changes in geolocation?

我有一个 App 组件是:

import Home from './screens/Home';
import * as React from 'react';

const App = () => {
  return <Home />;
};

export default App;

我的主页组件如下所示:

  export default class Home extends React.PureComponent {
  render() {
    return (
      <>
        <View style={styles.container}>
          <Text style={styles.heading}> Location Manager </Text>
          <CurrentLocation />
          <LocationList />
        </View>
        <ClearButton />
      </>
    );
  }
}

我编写了一个监视位置变化的组件: 它看起来像:

export const useGeolocation = (): [string, GeolocationData] => {
  const [error, setError] = useState('');
  const [position, setPosition] = useState<GeolocationData>({
    latitude: 0,
    longitude: 0,
  });

  useEffect(() => {
    const watchId = Geolocation.watchPosition(
      (pos) => {
        setError('');
        setPosition({
          latitude: pos.coords.latitude,
          longitude: pos.coords.longitude,
        });
      },
      (e) => setError(e.message),
    );
    return () => Geolocation.clearWatch(watchId);
  }, []);

  return [error, position];
};

现在我该如何使用这个组件?我把这个放在哪里?我在教程中读到它会在用户不使用应用程序(后台)或组件将卸载时取消订阅?如何实现?

下次试试。只需导入并使用 :)

import { useGeolocation } from './useGeolocation';
import Home from './screens/Home';
import * as React from 'react';

const App = () => {
  const geoLocation = useGeolocation();
  return <Home gl={geoLocation} />;
};

export default App;