如何在我的eventHandler中访问React状态? [英] How can I access React state in my eventHandler?

查看:35
本文介绍了如何在我的eventHandler中访问React状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的状态:

const [markers, setMarkers] = useState([])

我在useEffect钩子中初始化Leaflet映射.它具有 click eventHandler.

I initialise a Leaflet map in a useEffect hook. It has a click eventHandler.

useEffect(() => {
    map.current = Leaflet.map('mapid').setView([46.378333, 13.836667], 12)
    .
    .
    .
    map.current.on('click', onMapClick)
}, []

在该 onMapClick 里面,我在地图上创建了一个标记并将其添加到状态:

Inside that onMapClick I create a marker on the map and add it to the state:

const onMapClick = useCallback((event) => {
    console.log('onMapClick markers', markers)
    const marker = Leaflet.marker(event.latlng, {
        draggable: true,
        icon: Leaflet.divIcon({
            html: markers.length + 1,
            className: 'marker-text',
        }),
    }).addTo(map.current).on('move', onMarkerMove)

    setMarkers((existingMarkers) => [ ...existingMarkers, marker])
}, [markers, onMarkerMove])

但是我也想在这里访问 markers 状态.但我无法在此处阅读 markers .始终是初始状态.我试图通过按钮的onClick处理程序调用 onMapClick .在那里我可以阅读 markers .如果原始事件始于地图,为什么我不能阅读 markers ?如何在 onMapClick 内读取状态变量?

But I would also like to access the markers state here. But I can't read markers here. It's always the initial state. I tried to call onMapClick via a onClick handler of a button. There I can read markers. Why can't I read markers if the original event starts at the map? How can I read the state variables inside onMapClick?

这里是一个示例: https://codesandbox.io/s/jolly-mendel-r58zp?file =/src/map4.js 当您单击地图并查看控制台时,会发现 onMapClick 中的 markers 数组在填入 useEffect 时保持为空>会监听 markers .

Here is an example: https://codesandbox.io/s/jolly-mendel-r58zp?file=/src/map4.js When you click in the map and have a look at the console you see that the markers array in onMapClick stays empty while it gets filled in the useEffect that listens for markers.

推荐答案

反应状态是异步的,它不会立即保证您为您提供新状态,关于您的问题为什么我不能阅读标记如果原始事件在地图上开始,则该事件是异步的,并且状态值由函数根据其当前的关闭状态和状态更新使用,这一事实将反映在下一次重新渲染中,现有的关闭状态不会受到影响但是会创建新的实例,因为您拥有 this 实例(具有全局范围),所以您不会在类组件上遇到此问题.

React state is asynchronous and it won't immediately guarantee you to give you the new state, as for your question Why can't I read markers if the original event starts at the map its an asynchronous nature and the fact that state values are used by functions based on their current closures and state updates will reflect in the next re-render by which the existing closures are not affected but new ones are created, this problem you wont face on class components as you have this instance in it, which has global scope.

作为开发组件,我们应该确保从调用位置控制组件,而不是处理状态的函数闭包,它会在每次状态更改时重新呈现.您的解决方案是可行的,无论何时需要将传递给函数的事件或操作传递给它,都应传递一个值.

As a developing a component , we should make sure the components are controlled from where you are invoking it, instead of function closures dealing with state , it will re-render every time state changes . Your solution is viable you should pass a value whatever event or action you pass to a function, when its required.

-它仅通过传递params或deps来使用useEffect并将回叫包装在其中,就您的情况而言

- its Simple just pass params or deps to useEffect and wrap your callback inside, for your case it would be

useEffect(() => {
    map.current = Leaflet.map('mapid').setView([46.378333, 13.836667], 12)
    .
    .
    .
    map.current.on('click',()=> onMapClick(markers)) //pass latest change
}, [markers] // when your state changes it will call this again

更多信息,请查看以下内容 https://dmitripavlutin.com/react-hooks-stale-closures/,它将长期帮助您!!!

for more info check this one out https://dmitripavlutin.com/react-hooks-stale-closures/ , it will help you for longer term !!!

这篇关于如何在我的eventHandler中访问React状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆