
在react native应用中集成应用内购买(in-app purchase, iap)功能时,react-native-iap是一个广泛使用的库。开发者通常会首先通过该库获取商品详情,然后尝试发起购买请求。然而,在某些情况下,尤其是在库版本更新后,尝试调用iap.requestsubscription或iap.requestpurchase等方法时,可能会遇到一个typeerror: right operand of 'in' is not an object的错误。
这个错误通常发生在已经成功获取到商品(如订阅)的详细信息,并且这些信息看起来是正确的对象(例如,包含productId等字段),但在将productId作为字符串直接传递给购买方法时,库内部期望一个对象类型,从而导致类型不匹配错误。
react-native-iap库在不断迭代和更新,其API签名也可能随之变化。导致上述TypeError的根本原因在于,新版本的requestPurchase或requestSubscription方法不再直接接受一个字符串形式的productId作为参数,而是期望一个结构化的对象。这个对象需要明确指定商品ID的键名,并且这个键名在iOS和Android平台之间有所不同。
具体来说:
如果直接传入一个字符串,或者传入的对象结构不正确,库内部在尝试访问预期的属性时就会失败,从而抛出TypeError。
解决此问题的关键在于,在调用购买方法之前,根据当前运行的平台动态构建正确的参数对象。我们可以利用Platform.OS来判断当前是iOS还是Android,然后创建相应的参数结构。
以下是一个通用的函数示例,用于根据平台生成正确的购买参数对象:
import { Platform } from 'react-native';
import * as RNIap from 'react-native-iap'; // 假设你导入的库名为 RNIap
/**
* 根据平台构建购买请求所需的参数对象
* @param {string} productId 要购买的商品ID
* @returns {object} 购买请求参数对象
*/
const getPurchaseParams = (productId) => {
if (Platform.OS === 'ios') {
return { sku: productId };
} else { // Android
return { skus: [productId] };
}
};
// 或者更简洁地直接在调用处判断
// let purchaseParams = Platform.OS === "ios" ? { sku: prod_id } : { skus: [prod_id] };结合原始问题中的代码片段,我们可以这样修改requestGoogleSubscription函数,以正确地发起购买请求:
import React, { useState, useEffect } from 'react';
import { Platform } from 'react-native';
import * as Iap from 'react-native-iap'; // 假设你导入的库名为 Iap
// 假设 selectedPlan 和 Sentry 已经定义
// const selectedPlan = { google_pay_id: 'weekly_subscription_3' };
// const Sentry = { captureMessage: (msg, err) => console.log(msg, err) };
function SubscriptionComponent({ selectedPlan }) {
const [googleSub, setGoogleSub] = useState(null);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
(async () => {
try {
// 确保 selectedPlan.google_pay_id 存在且有效
if (!selectedPlan || !selectedPlan.google_pay_id) {
console.warn('selectedPlan or google_pay_id is missing.');
return;
}
const subs = await Iap.getSubscriptions([selectedPlan.google_pay_id]);
if (subs && subs.length > 0) {
console.log('Subscriptions response: ', subs);
setGoogleSub(subs[0]);
}
} catch (error) {
Sentry.captureMessage('Failed to get Google subscriptions', error);
console.error(error);
}
})();
}, [selectedPlan]);
const requestGoogleSubscription = async () => {
try {
setIsLoading(true);
console.log('requestGoogleSubscription: googleSub', googleSub);
if (googleSub && typeof googleSub === 'object' && googleSub.productId) {
console.log('requestGoogleSubscription: initiating purchase');
// *** 核心修改部分 ***
// 根据平台构建正确的参数对象
let purchaseParams;
if (Platform.OS === 'ios') {
purchaseParams = { sku: googleSub.productId };
} else { // Android
purchaseParams = { skus: [googleSub.productId] };
}
// 使用构建好的参数对象调用 requestPurchase 或 requestSubscription
// 注意:根据你的 RNIAP 版本和具体需求,可能是 requestPurchase 或 requestSubscription
// 这里使用 requestPurchase 作为通用示例,与答案保持一致
const purchase = await Iap.requestPurchase(purchaseParams);
console.log('Purchase successful: ', purchase);
// 进一步处理购买成功后的逻辑,如验证收据等
} else {
console.warn('No valid Google subscription details available to initiate purchase');
}
} catch (error) {
Sentry.captureMessage('Failed Google subscription', error);
console.error('Purchase Error:', error); // 更具体的错误日志
} finally {
setIsLoading(false);
}
};
// 假设这里有一个按钮来触发 requestGoogleSubscription
return (
<div>
{/* ... 其他UI元素 ... */}
<button onClick={requestGoogleSubscription} disabled={isLoading}>
{isLoading ? '购买中...' : '购买订阅'}
</button>
</div>
);
}
export default SubscriptionComponent;TypeError: right operand of 'in' is not an object错误在使用react-native-iap发起应用内购买时,通常是由于库API签名更新,要求商品ID以特定对象结构({ sku: '...' }或{ skus: ['...'] })传入而非简单字符串引起的。通过在调用购买方法前根据平台动态构建正确的参数对象,可以有效解决此问题。开发者应始终关注所用库的最新文档,以确保代码与API保持同步,从而避免类似的类型错误。
以上就是React Native 应用内购TypeError错误:正确处理商品ID参数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号