在一种情况下触发了React的无穷尽linter规则,但另一种却没有触发?

时间:2019-06-04 20:29:37

标签: reactjs react-hooks

我想将此代码沙箱https://codesandbox.io/s/lx947qjv0z修改为我自己的React应用。我试图简单地useGoogleMap.js

import { useEffect, useState, useRef } from "react";
import GoogleMapsApiLoader from "google-maps-api-loader";

const apiKey = "AIzaSyCVBthtEmWi0Ul8mejDQrBlOULXB1kTB3I";

const eventsMapping = {
  onCenterChanged: ["center_changed", map => map.getCenter()],
  onBoundsChanged: ["bounds_changed", map => map.getBounds()]
};

export default function useGoogleMap({ zoom, center, events }) {
  const [mapState, setMapState] = useState({ loading: true });
  const mapRef = useRef();
  useEffect(() => {
    GoogleMapsApiLoader({ apiKey }).then(google => {
      const map = new google.maps.Map(mapRef.current, { zoom, center });
      Object.keys(events).forEach(eventName =>
        map.addListener(eventsMapping[eventName][0], () =>
          events[eventName](eventsMapping[eventName][1](map))
        )
      );

      setMapState({ maps: google.maps, map, loading: false });
    });
  }, []);
  return { mapRef, ...mapState };
}

以下内容(因为我不认为我需要events):

import {useState, useEffect, useRef } from 'react';
import GoogleMapsApiLoader from 'google-maps-api-loader';

const apiKey = process.env.REACT_APP_GOOGLE_MAPS_API_KEY;

export default function useGoogleMap(options) {
  const [mapState, setMapState] = useState();
  const mapRef = useRef();

  useEffect(() => {
    GoogleMapsApiLoader({ apiKey }).then(google => {
      const map = new google.maps.Map(mapRef.current, options);
      setMapState({ maps: google.maps, map });
    });
  }, [options]);
  return { mapRef, ...mapState };
}

在我自己的代码中,如果我从作为第二个参数传递给options的依赖项数组中省略了useEffect(),则会收到警告:

  

React Hook缺少依赖项:'options'

enter image description here

困扰我的是:为什么原始的沙盒代码没有这样的警告? zoomcenter也不依赖于它在useEffect()中的作用吗?

1 个答案:

答案 0 :(得分:1)

您发布的codeandbox也收到错误 enter image description here

本文可能会帮助https://reactjs.org/docs/hooks-faq.html#is-it-safe-to-omit-functions-from-the-list-of-dependencies

基本上,正在发生的事情是useEffect无法立即访问选项。因此,您需要像以下那样将选项作为参数传递给useEffect。...

export default function useGoogleMap(options) {
  const [mapState, setMapState] = useState({ loading: true });
  const mapRef = useRef();

  useEffect((options) => {

    GoogleMapsApiLoader({ apiKey }).then(google => {
      const map = new google.maps.Map(mapRef.current, options);

      setMapState({ maps: google.maps, map, loading: false });
    });
  }, []);
  return { mapRef, ...mapState };
}

那将消除您的错误!