GoogleMapReact 每 2 秒更改一次标记位置错误 - setState 不是函数

GoogleMapReact change marker location every 2 seconds error - setState is not a function

我的 React 应用程序中有以下 map.jsx 文件,它在屏幕上显示地图。我正在尝试向这张地图添加一个标记(在一个名为 'MyGreatPlace' 的单独组件中),它每 2 秒更改一次位置。它应该只更新标记而不是刷新整个地图,但是我收到以下错误:

Uncaught TypeError: setState is not a function

下面是我的代码:

import GoogleMapReact from 'google-map-react';
import './map.css';
import MyGreatPlace from './my_great_place.jsx';
import React, { useEffect, useRef, useState, setState } from 'react';

const Map = ({ location, zoomLevel, markerLat, markerLong }) => {

    useEffect(() => {
        const interval = setInterval(() => {
            changeMarkerLatitude();
        }, 2000);
        return () => clearInterval(interval);
    }, []);

    const changeMarkerLatitude = () => {
        setState({
            markerLat: markerLat + 50,
        });
    };

    return (
        <div className='map'>
            <div className='google-map'>
                <GoogleMapReact
                    bootstrapURLKeys={{ key: 'KeyID' }}
                    defaultCenter={location}
                    defaultZoom={zoomLevel}>
                    <MyGreatPlace lat={markerLat} lng={markerLong} text={'A'} />
                </GoogleMapReact>
            </div>
        </div>
    );
};

export default Map;

有谁知道我该如何解决这个错误,或者是否有更新标记位置的替代方法?

这不是您使用状态对象的方式。 useState 用于功能组件,您可以通过提供两个值来调用它。首先,对实际值的引用,其次 - 对 setter 的引用。因此 const [stateVal, setStateVal] = useState() 为您提供了对状态对象的未定义引用,以及对用于更新它的函数的引用。你永远不会直接改变状态(例如 stateVal = newVal)。您总是使用 setter 来改变状态(这会触发重新渲染)。您始终可以通过将值传递到 useState() 调用来初始化该值。像这样:setStateVal(newVal)

import GoogleMapReact from 'google-map-react';
import './map.css';
import MyGreatPlace from './my_great_place.jsx';
import React, { useEffect, useRef, useState, setState } from 'react';

const Map = ({ location, zoomLevel, markerLat, markerLong }) => {
    const [markerLatVal, setMarkerLatVal] = useState(markerLat) // You can put value in here to initialize

    useEffect(() => {
        const interval = setInterval(() => {
            changeMarkerLatitude();
        }, 2000);
        return () => clearInterval(interval);
    }, []);

    const changeMarkerLatitude = () => {
    // 'prev' gives you access to the previous state value
        setMarkerLatVal(prev => prev + 50);
    };

    return (
        <div className='map'>
            <div className='google-map'>
                <GoogleMapReact
                    bootstrapURLKeys={{ key: 'KeyID' }}
                    defaultCenter={location}
                    defaultZoom={zoomLevel}>
                    <MyGreatPlace lat={markerLat} lng={markerLong} text={'A'} />
                </GoogleMapReact>
            </div>
        </div>
    );
};

export default Map;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>