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

React Native Firebase云消息推送点击通知无法跳转页面求助

解决React Native FCM通知点击跳转页面的问题

嘿,我来帮你搞定这个FCM通知跳转的难题!你已经完成了权限请求和Token获取的基础步骤,接下来咱们得针对应用的不同运行状态(前台、后台、完全关闭)分别处理通知点击逻辑,同时确保配置和导航的衔接没问题。

第一步:先确认基础配置是否到位

Android端配置检查

打开android/app/src/main/AndroidManifest.xml,确保你的MainActivity添加了处理通知点击的intent-filter:

<activity
  android:name=".MainActivity"
  android:label="@string/app_name"
  android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
  android:launchMode="singleTask" <!-- 这个很重要,确保点击通知不会重复打开应用 -->
  android:windowSoftInputMode="adjustResize">
  <intent-filter>
      <action android:name="android.intent.action.MAIN" />
      <category android:name="android.intent.category.LAUNCHER" />
      <!-- 新增这行,让应用能接收通知点击的Intent -->
      <category android:name="android.intent.category.DEFAULT" />
  </intent-filter>
</activity>

另外要确认google-services.json已经放在android/app目录下,并且build.gradle配置了Firebase依赖。

iOS端配置检查

打开ios/[你的App名]/AppDelegate.m(或Swift版本的AppDelegate.swift),确保添加了FCM的通知处理代码:

#import <Firebase.h>
#import <RNFBApp/RNFBAppModule.h>
#import <RNFBMessaging/RNFBMessagingModule.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  // 其他初始化代码...
  [FIRApp configure];
  [RNFBMessagingModule didFinishLaunchingWithOptions:launchOptions];
  
  // 开启通知权限请求(也可以在RN代码里请求,但这里确保初始化正确)
  UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  center.delegate = self;
  [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound + UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
    // 处理权限结果
  }];
  [application registerForRemoteNotifications];
  
  return YES;
}

// 处理后台通知点击
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
  [RNFBMessagingModule didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

// 处理前台通知点击
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler
{
  [RNFBMessagingModule didReceiveNotificationResponse:response withCompletionHandler:completionHandler];
  completionHandler();
}

同时要在Xcode的Signing & Capabilities里开启Push Notifications和Background Modes下的Remote notifications权限。

第二步:RN代码中完善通知点击逻辑

FCM的通知处理分三种状态,你需要分别监听并处理:

1. 先配置导航Ref(以React Navigation为例)

要实现页面跳转,必须能访问导航实例。在你的根导航组件(比如App.js)里创建并导出导航Ref:

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import HomeScreen from './screens/HomeScreen';
import TargetScreen from './screens/TargetScreen';

const Stack = createStackNavigator();
// 导出导航Ref,方便其他组件调用
export let navigationRef;

function App() {
  return (
    <NavigationContainer ref={(ref) => navigationRef = ref}>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Target" component={TargetScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

2. 完善通知监听代码(类组件示例)

替换你原来的componentWillMount(建议用componentDidMount,因为componentWillMount已被废弃),添加完整的通知监听逻辑:

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import messaging from '@react-native-firebase/messaging';
// 导入导航Ref
import { navigationRef } from './App';

class NotificationHandler extends Component {
  componentDidMount() {
    // 请求通知权限
    messaging().requestPermissions()
      .then(() => console.log('权限请求成功'))
      .catch(err => console.log('权限请求失败:', err));

    // 获取FCM Token
    messaging().getToken()
      .then(token => console.log('FCM Token:', token))
      .catch(err => console.log('获取Token失败:', err));

    // 处理**前台**收到的通知:FCM前台不会自动弹出系统通知,需要自己构建本地通知
    messaging().onMessage(async remoteMessage => {
      await messaging().displayNotification({
        title: remoteMessage.notification.title,
        body: remoteMessage.notification.body,
        data: remoteMessage.data, // 携带跳转所需的自定义数据
      });
    });

    // 监听**后台**状态下点击通知的事件
    messaging().onNotificationOpenedApp(remoteMessage => {
      console.log('后台点击通知:', remoteMessage);
      this.handleNavigation(remoteMessage.data);
    });

    // 处理**应用完全关闭**时点击通知的事件
    messaging()
      .getInitialNotification()
      .then(remoteMessage => {
        if (remoteMessage) {
          console.log('关闭状态点击通知:', remoteMessage);
          this.handleNavigation(remoteMessage.data);
        }
      });
  }

  // 统一处理导航跳转逻辑
  handleNavigation = (data) => {
    // 从通知的data字段获取目标页面(发送通知时要携带这个字段)
    const targetScreen = data.targetScreen || 'Target';
    // 确保导航实例已就绪再跳转
    if (navigationRef.isReady()) {
      navigationRef.navigate(targetScreen);
    } else {
      // 如果导航还没就绪,延迟一下再跳转
      setTimeout(() => navigationRef.navigate(targetScreen), 500);
    }
  };

  render() {
    return (
      <View>
        <Text>通知处理组件</Text>
      </View>
    );
  }
}

export default NotificationHandler;

3. 注意通知的Payload格式

发送FCM通知时,必须在data字段里携带跳转所需的信息,示例Payload:

{
  "to": "你的FCM Token",
  "notification": {
    "title": "测试通知",
    "body": "点击跳转至目标页面"
  },
  "data": {
    "targetScreen": "Target",
    "otherParams": "自定义参数"
  }
}

第三步:常见问题排查

  • 确保你使用的是@react-native-firebase/messaging(而非旧版的react-native-fcm),并且RN版本≥0.60(自动链接依赖)。
  • iOS测试必须用真实设备,模拟器无法接收推送通知。
  • 检查应用的通知权限是否开启(设置→你的应用→通知)。
  • 确认导航Ref已正确设置,没有出现undefined的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:15:04