简体   繁体   English

无法使用 react useState 更新状态

[英]unable to update state using react useState

I am learning react hooks .我正在学习 react hooks In my code I have set the initial values for plotting map as在我的代码中,我将绘制地图的初始值设置为

//map state
const [mapData, setMapData] = useState(
    { lat: 40.712776, lng: -74.0059, zoom: 5 }
);

In the useEffect() call back I am loading the map onceuseEffect()回调中,我正在加载地图一次

useEffect(() => {
    initMap();
}, []); // run once

Inside the initMap() there is map.on() method to get the updated geo locations.initMap()map.on()方法来获取更新的地理位置。 The initMap() is initMap()

const initMap = () => {
    mapboxgl.accessToken = 'token';
    const map = new mapboxgl.Map({
        container: mapContainer,
        style: 'mapbox://styles/mapbox/streets-v11',
        center: [mapData.lng, mapData.lat],
        zoom: mapData.zoom
    }); // load the map with init values

    // update the `mapData` as map move
    map.on('moveend', () => {
        const { lng, lat } = map.getCenter(); // logs the updated lat and lon
        setMapData({ lat: lat.toFixed(4), lng: lng.toFixed(4), zoom: map.getZoom().toFixed(2) }); // suppose to set the updated value
        console.log(mapData); // not logging updated values!
    });
}

The setMapData() is not setting the state. setMapData()没有设置状态。 But the map.on is called and is logging the values.但是map.on被调用并记录值。

setState is asynchronous, updated state may or may not be available to statements following it. setState是异步的,更新后的状态可能会或可能不会用于跟随它的语句。

Use an effect hook that runs on a mapData update to react to changes.使用在 mapData 更新上运行的效果挂钩来对更改做出反应。

useEffect(() => console.log(mapData), [mapData])

This is also the case for useSelector. useSelector 也是如此。 I don't believe React Hooks is being supported by Mapbox in this way.我不相信 Mapbox 以这种方式支持 React Hooks。 I have event handlers I add onto my map and those handlers cannot access the current values of the component's useState/useSelector.我在地图上添加了事件处理程序,但这些处理程序无法访问组件的 useState/useSelector 的当前值。 These values are always the values they were when the event handlers were added to the map.这些值始终是将事件处理程序添加到地图时的值。 I have resorted to adding another state that triggers useEffects instead of handling it all in my event handler.我已经求助于添加另一个触发 useEffects 的状态,而不是在我的事件处理程序中处理它。

edit: It was brought to my attention that you can use redux's 'useStore' hook to grab the current redux store even in the Mapbox event handlers!编辑:我注意到即使在 Mapbox 事件处理程序中,您也可以使用 redux 的“useStore”钩子来获取当前的 redux 存储! It's tougher to test, however, bc you have to mock the 'useStore' manually.但是,测试更困难,因为您必须手动模拟“useStore”。 Hope that helps!希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM