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

问题描述 投票: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];
};

现在如何使用此组件?我该放在哪里?我在一个教程中阅读了该教程,当用户不使用应用程序(后台)时,它将取消订阅,否则组件将被卸载?如何实现?

android ios react-native geolocation react-hooks
1个回答
0
投票

如果使用路由器v4,则应使用withRouter

import React, { useEffect } from 'react'
import { withRouter } from 'react-router-dom'

const Component = ({ history }) => {
    useEffect(() => history.listen(() => {
        // do something on route change
        // for my example, close a drawer
    }), [])

    //...
}

export default withRouter(Component)

How to listen to route changes in react router v4?

更多信息:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/hooks.md

© www.soinside.com 2019 - 2024. All rights reserved.