如何使用观察地理位置变化的地理定位组件?

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

我有一个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];
};

现在我该如何使用这个组件?我在一个教程上看到,当用户不使用App(后台)时,它会取消订阅,或者组件会卸载?如何实现?

reactjs react-native geolocation react-hooks
1个回答
1
投票

下一个尝试。只要导入它并使用:)

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;
© www.soinside.com 2019 - 2024. All rights reserved.