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

react-native-push-notification configure方法返回数据为null如何解决?

修复react-native-push-notification中notification.data为null的问题

以下是针对该问题的具体排查和修复步骤:

1. 检查推送Payload格式

确保推送的Payload结构符合平台要求,自定义数据需放在正确位置:

  • Android端:自定义数据必须嵌套在data字段中,示例:
    {
      "title": "订单通知",
      "message": "您的订单已发货",
      "data": {
        "actionId": "pay",
        "id": "1001"
      },
      "channelId": "your-channel-id"
    }
    
  • iOS端:自定义数据不能放在aps字段内,需直接作为顶级字段,react-native-push-notification会自动将这些字段合并到notification.data中,示例:
    {
      "aps": {
        "alert": {
          "title": "订单通知",
          "body": "您的订单已发货"
        }
      },
      "actionId": "pay",
      "id": "1001"
    }
    

2. 兼容不同平台的数据字段位置

部分场景下,自定义数据可能直接挂载在notification根节点而非data下(比如iOS推送),可以调整代码做兼容处理:

React.useEffect(() => {
  PushNotification.configure({
    onNotification(notification) {
      console.log('完整通知对象:', notification);
      // 兼容iOS和Android的字段差异
      const actionId = notification.data?.actionId || notification.actionId;
      const id = notification.data?.id || notification.id;

      if (actionId && id) {
        AsyncStorage.setItem('actionId', actionId);
        AsyncStorage.setItem('orderId', id);
      }
    },
  });
}, []);

3. 检查Android端配置完整性

  • 确保已创建并配置通知渠道,推送时指定对应channelId:
    PushNotification.createChannel(
      {
        channelId: "order-channel", // 必填
        channelName: "订单通知渠道",
        channelDescription: "用于接收订单相关通知",
      },
      (created) => console.log(`渠道创建状态: ${created}`)
    );
    
  • 确认AndroidManifest.xml中已添加必要的广播接收器和权限,避免数据传递被拦截:
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />
    
    <receiver
        android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationReceiver"
        android:exported="false" >
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </receiver>
    <service android:name="com.dieam.reactnativepushnotification.modules.RNPushNotificationListenerService" android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    

4. 升级依赖版本

部分旧版本的react-native-push-notification存在数据传递bug,建议升级到最新稳定版,同时确保@react-native-community/push-notification-ios(iOS端依赖)版本匹配。

5. Android后台推送注意事项

如果使用Firebase云消息推送,后台状态下需发送Data消息而非Notification消息——系统会直接处理Notification消息,导致自定义数据无法传递到onNotification回调中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 16:15:57