【问题标题】:unable to update state using react useState无法使用 react useState 更新状态
【发布时间】:2019-10-17 18:13:27
【问题描述】:

我正在学习反应 hooks。在我的代码中,我将绘制地图的初始值设置为

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

在useEffect() 回调中,我正在加载地图一次

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

在initMap() 内部有map.on() 方法来获取更新的地理位置。 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!
    });
}

setMapData() 未设置状态。但是map.on 被调用并记录了这些值。

【问题讨论】:

  • 你怎么知道状态没有被设置? setState 是异步的。它只保证在另一个对其做出反应的钩子上可用。
  • 在此处查看 Chris 的回答:stackoverflow.com/questions/55265255/…

标签: javascript reactjs mapbox react-hooks


【解决方案1】:

setState 是异步的,更新后的状态可能对跟随它的语句可用,也可能不可用。

使用在 mapData 更新上运行的效果挂钩来响应更改。

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

【讨论】:

  • 阿文是正确的。通过将mapData 添加到数组中,react 将在此值更改(以及初始挂载)时调用useEffect()。
  • 这个有什么问题?这正是规范所说的。
【解决方案2】:

useSelector 也是如此。 我不相信 Mapbox 以这种方式支持 React Hooks。 我有添加到地图上的事件处理程序,这些处理程序无法访问组件的 useState/useSelector 的当前值。这些值始终是事件处理程序添加到地图时的值。 我已经求助于添加另一个触发 useEffects 的状态,而不是在我的事件处理程序中处理它。

编辑: 引起我注意的是,即使在 Mapbox 事件处理程序中,您也可以使用 redux 的“useStore”钩子来获取当前的 redux 存储! 但是,测试更难,因为您必须手动模拟“useStore”。 希望对您有所帮助!

【讨论】:

  • 我错误地看到了这条评论,我的问题甚至与问题无关,但你的回答让我意识到我可以使用useSelector 而避免使用useStore - 我的东西将不得不进一步研究,但这是一个巨大的帮助和很好的起点来学习一些东西,非常感谢!
猜你喜欢
  • 2020-07-08
  • 1970-01-01
  • 2020-05-12
  • 2020-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-18
相关资源
最近更新 更多