警告:传递给 useMemo 的最后一个参数在渲染之间改变了大小。这个数组的顺序和大小必须保持不变

Warning: The final argument passed to useMemo changed size between renders. The order and size of this array must remain constant

我在用户输入位置时获取标记,然后将标记列表提供给 Google 地图组件。因为我不希望地图每次都重新渲染,所以我已经记住了它。它仅在标记道具更改时重新渲染。但是当标记发生变化时,我收到以下警告:

Warning: The final argument passed to useMemo changed size between renders. The order and size of this array must remain constant.

我遵循了其他帖子中的答案,none 对我有用。我做错了什么?

const [plants, setPlants] = useState([
    {
      name: "Plant 1",
      id: uuidv4(),
      location: "",
      coords: {},
      country: "",
      isOffshore: false,
    },
  ]);

  const isObjectEmpty = (obj) => {
    for (var i in obj) return false;
    return true;
  };

  const getMarkers = () => {
    var temp = [];
    for (var i = 0; i < plants.length; i++)
      if (!isObjectEmpty(plants[i].coords)) temp.push(plants[i].coords);
    return temp;
  };

  const markers = useMemo(
    () => getMarkers(),
    [...plants.map((item) => item.coords)]
  );

我的地图组件:

const MapContainer = React.memo((props) => {
  const [map, setMap] = useState();
  const [center, setCenter] = useState({ lat: 59.913, lng: 10.75 });
  var bounds = new props.google.maps.LatLngBounds();

  const setMapObj = (mapProps, map) => {
    setMap(map);
  };

  useDeepCompareEffect(() => {
    console.log(props.markers);
    if (props.markers.length < 1) return;
    setCenter(props.markers[props.markers.length - 1]);
    //this is to zoom out the map by bit;
    //we provide bounds but not the marker
    // if (props.markers.length === 1) {
    //   bounds.extend(
    //     new props.google.maps.LatLng(props.markers[0].lat, props.markers[0].lng)
    //   );
    //   bounds.extend(
    //     new props.google.maps.LatLng(
    //       props.markers[0].lat - 1,
    //       props.markers[0].lng - 1
    //     )
    //   );
    //   map && map.fitBounds(bounds);
    //   return;
    // }
    // for (var i = 0; i < props.markers.length; i++) {
    //   bounds.extend(
    //     new props.google.maps.LatLng(props.markers[i].lat, props.markers[i].lng)
    //   );
    // }
    // if (map) {
    //   map.fitBounds(bounds);
    // }
  }, [props.markers, map]);

  return (
    <div className={props.className}>
      <Map
        google={props.google}
        style={{ borderRadius: "10px" }}
        center={center}
        initialCenter={{ lat: 59.913, lng: 10.75 }}
        onReady={setMapObj}
        zoom={7}
      >
        {props.markers.map((item, index) => {
          if (item.lat && item.lng)
            return (
              <Marker key={index} position={{ lat: item.lat, lng: item.lng }} />
            );
        })}
      </Map>
    </div>
  );
});

 const markers = useMemo(
    () => getMarkers(),
    [...plants.map((item) => item.coords)]
  );

如果坐标是 [[1,2],[3,4],[4,5]],您实际上是将 [[1,2],[3,4],[4,5]] 作为依赖项传递。

你应该只使用

 const markers = useMemo(
    () => getMarkers(),
    [plants]
  );