javascript - react native DeviceEventEmitter 取消订阅事件

标签 javascript react-native events event-handling

我正在使用 DeviceEventEmitter 来处理最喜欢的方法的事件,该方法已在构造函数中订阅:

DeviceEventEmitter.addListener("FavoriteClick", async (e) => 
{
    // do something
})

只要组件卸载(永久),此事件监听器就会保持事件状态。我必须调用什么取消订阅?我尝试将事件存储为变量并在 componentWillUnmount() 中调用 listener.removeCurrentListener() like the (limited) documentation states ,如果我理解正确的话,但是 removeCurrentListener() 不是一个方法。

最佳答案

DeviceEventEmitterdeprecated ,您应该改用 NativeEventEmitter

Example :

import { NativeEventEmitter, NativeModules } from 'react-native';

const { CalendarManager } = NativeModules;

const calendarManagerEmitter = new NativeEventEmitter(CalendarManager);

const subscription = calendarManagerEmitter.addListener(
  'EventReminder',
  (reminder) => console.log(reminder.name)
);

...

// Don't forget to unsubscribe, typically in componentWillUnmount
subscription.remove();

关于javascript - react native DeviceEventEmitter 取消订阅事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58285364/

相关文章:

javascript - 用 C 在服务器上处理 javascript XMLHttpRequest

react-native - 没有堆栈',原因 : 'Unhandled JS Exception: Invalid regular expression: invalid group specifier name

JavaScript 事件 : hook when image starts loading ( already has naturalWidth & naturalHeight props but haven't loaded itself yet)

javascript - D3.js - 无法读取未定义的属性 'axis'

javascript - 谷歌图表 API : Change color on hovering legend

javascript - 使用 Google Places API 和 KnockoutJS 列出地名

ios - React Native 与 Appsee 中的触摸手势问题

javascript - 在我的案例中,如何使用 createSwitchNavigator 从注销导航到登录屏幕?

events - JQuery:如何查看元素上定义了哪些事件?

python - unix 上的重复设备输入事件 (/dev/input/event)