如何将基于类的生命周期方法转换为功能方法?

时间:2019-12-08 02:50:22

标签: javascript reactjs react-native class expo

在以下代码中:

  componentDidMount() {
    registerForPushNotificationsAsync();
    this._notificationSubscription = Notifications.addListener(this._handleNotification);
  }

Notifications.addListener(this._handleNotification);分配给this._notificationSubscription和简单地进行操作之间有什么区别:

  componentDidMount() {
    registerForPushNotificationsAsync();
    Notifications.addListener(this._handleNotification);
  }

还要如何将其转换为如下所示的功能组件格式?

    useEffect(() => {
        registerForPushNotificationsAsync();
        Notifications.addListener(handleNotification);
    }, []);

1 个答案:

答案 0 :(得分:0)

useEffect(() => {
        registerForPushNotificationsAsync();
        const subscription =Notifications.addListener(handleNotification);
        return () => {
            // Call method for clear subscription. I asume that it is remove but it can be another
            subscription.remove()
        }
    }, []);
相关问题