切换状态时,功能组件事件仍然处于活动状态 - React Mapbox
我正在尝试构建一个应用程序,您可以通过单击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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当我开始使用React Hooks时,我遇到了同样的问题!
不用担心,这是因为您没有代码可以删除添加的
单击
map
ref的事件!因此,您只需要清理
单击
映射对象的事件!请这样尝试..祝你好运..
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 formap
Ref!So you just need to cleanup the
click
event for the map object!Please try this way.. Good luck..