【问题标题】:How to use a geolocation component that watches changes in geolocation?如何使用监视地理位置变化的地理位置组件?
【发布时间】:2020-06-04 20:27:09
【问题描述】:

我有一个 App 组件是:

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

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

export default App;

我的 home 组件如下所示:

  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];
};

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

【问题讨论】:

    标签: android ios react-native geolocation react-hooks


    【解决方案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;
    

    【讨论】:

    • 但我只是在监听位置变化?为什么需要路由器?
    • 问得好,也许你真的不需要路由器。让我考虑几分钟。
    • 天哪,当您询问位置时,您会谈论地理位置吗?
    • 更正确的问题是:如何使用一个地理定位组件来监视地理位置的变化?
    • 哦,现在我明白了!非常感谢:)
    猜你喜欢
    • 2013-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    相关资源
    最近更新 更多