React Native集成Google Mobile Ads插屏广告失效求助
问题分析与解决方案
你的代码仅完成了广告加载监听与状态更新,但未触发插屏广告的展示逻辑,这是广告不显示的核心原因。interstitial.show()的正确放置位置有两种常用实现方式:
方式一:在广告加载完成的回调中直接展示
当AdEventType.LOADED事件触发时,说明广告已加载完毕,此时直接调用show()即可自动展示广告:
import React, { useEffect, useState } from 'react'; import { View, Text } from 'react-native'; // 补上缺失的组件导入 import { InterstitialAd, AdEventType, TestIds } from 'react-native-google-mobile-ads'; const adUnitId = __DEV__ ? TestIds.INTERSTITIAL : 'ca-app-pub-xxxxxxxxxxxxxxxx/yyyyyyyyyy'; const interstitial = InterstitialAd.createForAdRequest(adUnitId, { requestNonPersonalizedAdsOnly: true, keywords: ['fashion', 'clothing'], }); function App() { const [loaded, setLoaded] = useState(false); useEffect(() => { const unsubscribe = interstitial.addAdEventListener(AdEventType.LOADED, () => { setLoaded(true); interstitial.show(); // 广告加载完成后立即展示 }); // 监听广告关闭事件,关闭后重新加载广告以便后续展示 interstitial.addAdEventListener(AdEventType.CLOSED, () => { interstitial.load(); setLoaded(false); }); interstitial.load(); return unsubscribe; }, []); return ( <View> <Text>Hello World</Text> </View> ); }
方式二:通过监听loaded状态变化触发展示
如果需要结合业务逻辑灵活控制展示时机,可通过useEffect监听loaded状态变化,当状态变为true时调用展示方法:
import React, { useEffect, useState } from 'react'; import { View, Text } from 'react-native'; import { InterstitialAd, AdEventType, TestIds } from 'react-native-google-mobile-ads'; const adUnitId = __DEV__ ? TestIds.INTERSTITIAL : 'ca-app-pub-xxxxxxxxxxxxxxxx/yyyyyyyyyy'; const interstitial = InterstitialAd.createForAdRequest(adUnitId, { requestNonPersonalizedAdsOnly: true, keywords: ['fashion', 'clothing'], }); function App() { const [loaded, setLoaded] = useState(false); useEffect(() => { const unsubscribe = interstitial.addAdEventListener(AdEventType.LOADED, () => { setLoaded(true); }); interstitial.addAdEventListener(AdEventType.CLOSED, () => { interstitial.load(); setLoaded(false); }); interstitial.load(); return unsubscribe; }, []); // 监听loaded状态,变为true时展示广告 useEffect(() => { if (loaded) { interstitial.show(); } }, [loaded]); return ( <View> <Text>Hello World</Text> </View> ); }
额外注意事项
- 必须补上
View和Text的导入,否则组件会报错无法渲染,广告也无法触发展示; - 建议监听
AdEventType.CLOSED事件,在广告关闭后重新加载广告,保证后续可再次展示; - 测试环境下若仍不显示广告,检查是否正确使用
TestIds.INTERSTITIAL测试ID,或是否符合谷歌广告的测试设备配置要求。
内容的提问来源于stack exchange,提问作者Rainul Hassan
相关产品推荐
相关产品推荐

