React Native 中的地理位置连续运行

Geolocation in react native runs continously

我尝试创建一个简单的 React Native 应用程序,并使用 react-native-maps 在地图中显示我的位置。

const [coordinate, setCoordinate] = useState()

    const getCoordinate = () => {
      navigator.geolocation.getCurrentPosition(data => {
        setCoordinate({
          latitude: data.coords.latitude,
          longitude: data.coords.longitude,
        });
      });
    }

    useEffect(() => {
      getCoordinate();
    })

代码工作正常,我得到了我的位置,用标记标记。我的问题是为什么 getCoordinate 函数不断地调用自己,并且 运行 不间断 ?

您没有将第二个参数传递给 useEffect(它应该是一个依赖项数组),这导致它在每次渲染时 运行。

因为你只希望它 运行 一次(基本上是在挂载上),你需要将一个空数组作为第二个参数传递给你的 useEffect:

useEffect(() => {
  getCoordinate();
}, [])