切换状态时,功能组件事件仍然处于活动状态 - React Mapbox

发布于 2025-01-30 18:14:35 字数 531 浏览 2 评论 0原文

我正在尝试构建一个应用程序,您可以通过单击Navitems来切换效果。

在导航项目上,我有一个事件侦听器,可以切换说明

const [marker, setMarker] = useState(false);

onClick={() => setMarker(!marker)}

该想法是将其设置为true时,您可以单击地图以设置航路点。当它是错误的时,单击会执行默认行为。

我尝试使用这样的if语句,

    if (marker) {
      map.current.on('click', (e) => {
        new mapboxgl.Marker().setLngLat(e.lngLat).addTo(map.current);
        // Create a new marker.
      });
    }

无论状态是真的还是错误,您仍然可以在第一次切换后将其放置。

有人可以告诉我我在这里想念什么吗?我知道这很愚蠢。

I'm trying to build an app where you can toggle effects by clicking on the navitems.

On the nav items I have an event listener that toggles state

const [marker, setMarker] = useState(false);

onClick={() => setMarker(!marker)}

The idea is when it's set to true, you can click on the map to set a waypoint. And when it's false, clicking does the default behavior.

I tried using an if statement like this

    if (marker) {
      map.current.on('click', (e) => {
        new mapboxgl.Marker().setLngLat(e.lngLat).addTo(map.current);
        // Create a new marker.
      });
    }

Whether state is true or false, you can still place a waypoint after toggling it for the first time.

Can someone please tell me what I'm missing here? I know it's something stupid.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无悔心 2025-02-06 18:14:35

当我开始使用React Hooks时,我遇到了同样的问题!
不用担心,这是因为您没有代码可以删除添加的单击 map ref的事件!
因此,您只需要清理单击映射对象的事件!

useEffect(() => {
    function clickHandler(e) {
        new mapboxgl.Marker().setLngLat(e.lngLat).addTo(map.current);
        // Create a new marker.
    }
    if (marker) {
        map.current.on('click', (e) => {
            clickHandler(e)
        });
    }
    return () => {
        map.current.removeEventListener('click', clickHandler)
    }
}, [marker]);

请这样尝试..祝你好运..

I've faced the same problem when I began to use React Hooks!
Don't worry, that's because you have no code for removing the added click event for map Ref!
So you just need to cleanup the click event for the map object!

useEffect(() => {
    function clickHandler(e) {
        new mapboxgl.Marker().setLngLat(e.lngLat).addTo(map.current);
        // Create a new marker.
    }
    if (marker) {
        map.current.on('click', (e) => {
            clickHandler(e)
        });
    }
    return () => {
        map.current.removeEventListener('click', clickHandler)
    }
}, [marker]);

Please try this way.. Good luck..

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文