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

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


每当组件卸下(永久)时,此事件侦听器将保持活动状态。我必须致电取消订阅吗?如果我正确理解,我尝试将事件存储为变量,并在listener.removeCurrentListener() like the (limited) documentation states中调用componentWillUnmount(),但是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();

09-03 18:05