You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native项目升级后通知模块错误求助:addListener未定义及权限弃用

问题解决方案

1. 替换已弃用的expo-permissions

expo-permissions已被拆分到各功能对应包中,通知相关权限现在直接通过expo-notifications提供的方法处理:

  • 先卸载废弃包:
    expo uninstall expo-permissions
    
  • 代码中替换权限请求逻辑,使用expo-notifications的requestPermissionsAsync方法:
    import * as Notifications from 'expo-notifications';
    
    // 请求通知权限
    const requestNotificationPermissions = async () => {
      const { status } = await Notifications.requestPermissionsAsync();
      return status === 'granted';
    };
    

2. 修复Notifications.addListener未定义报错

expo-notifications已移除addListener方法,改用两个细分方法分别处理通知接收和点击事件:

  • 替换原有监听逻辑:
    // 原错误写法
    // Notifications.addListener(handleNotification);
    
    // 监听通知接收事件
    const notificationReceivedListener = Notifications.addNotificationReceivedListener(notification => {
      // 自定义处理收到通知的逻辑
      console.log('收到通知:', notification);
    });
    
    // 监听通知点击响应事件
    const notificationResponseListener = Notifications.addNotificationResponseReceivedListener(response => {
      // 自定义处理用户点击通知后的逻辑
      console.log('通知被点击:', response);
    });
    
    // 组件卸载时移除监听,避免内存泄漏
    useEffect(() => {
      return () => {
        notificationReceivedListener.remove();
        notificationResponseListener.remove();
      };
    }, []);
    

AuthScreen代码修改示例

结合上述修改,调整后的AuthScreen代码大概如下:

import React, { useEffect, useState } from 'react';
import { View, Button, Text } from 'react-native';
import * as Notifications from 'expo-notifications';

const AuthScreen = () => {
  const [hasNotificationPerm, setHasNotificationPerm] = useState(false);

  useEffect(() => {
    checkNotificationPermissions();
    setupNotificationListeners();
  }, []);

  const checkNotificationPermissions = async () => {
    const { status } = await Notifications.getPermissionsAsync();
    if (status !== 'granted') {
      const { status: newStatus } = await Notifications.requestPermissionsAsync();
      setHasNotificationPerm(newStatus === 'granted');
    } else {
      setHasNotificationPerm(true);
    }
  };

  const setupNotificationListeners = () => {
    const receivedListener = Notifications.addNotificationReceivedListener(notification => {
      // 这里写处理通知接收的逻辑,比如展示本地提示
    });

    const responseListener = Notifications.addNotificationResponseReceivedListener(response => {
      // 这里写处理通知点击的逻辑,比如跳转到对应页面
    });

    return () => {
      receivedListener.remove();
      responseListener.remove();
    };
  };

  return (
    <View style={{ padding: 20 }}>
      <Text>通知权限状态:{hasNotificationPerm ? '已授权' : '未授权'}</Text>
      <Button title="重新申请通知权限" onPress={checkNotificationPermissions} />
      {/* 原有AuthScreen的UI组件 */}
    </View>
  );
};

export default AuthScreen;

内容的提问来源于stack exchange,提问作者user20659824

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 01:45:26