最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - react native DeviceEventEmitter unsubscribe from event - Stack Overflow

programmeradmin4浏览0评论

I'm using DeviceEventEmitter to handle events of a favorite method, to which is subscribed in the constructor:

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

This event listener stays active whenever the ponents unmounts (permenantly). What do I have to call to unsub? I've tried storing the event as a variable and calling listener.removeCurrentListener() in the ponentWillUnmount() like the (limited) documentation states, if I understand that correctly, but removeCurrentListener() is not a method.

I'm using DeviceEventEmitter to handle events of a favorite method, to which is subscribed in the constructor:

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

This event listener stays active whenever the ponents unmounts (permenantly). What do I have to call to unsub? I've tried storing the event as a variable and calling listener.removeCurrentListener() in the ponentWillUnmount() like the (limited) documentation states, if I understand that correctly, but removeCurrentListener() is not a method.

Share Improve this question asked Oct 8, 2019 at 11:19 Sander KoldenhofSander Koldenhof 1,2934 gold badges14 silver badges28 bronze badges 1
  • addListener returns an EmitterSubscription, which has the inherent method ".remove()". Therefore, your code should look like this: const favoriteClickSub = DeviceEventEmitter.addListener("FavoriteClick", (e) => {}); favoriteClickSub.remove(); – sansa Commented Jul 22, 2021 at 11:19
Add a ment  | 

1 Answer 1

Reset to default 12

DeviceEventEmitter is deprecated, you should use NativeEventEmitter instead.

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 ponentWillUnmount
subscription.remove();
发布评论

评论列表(0)

  1. 暂无评论