未定义不是对象(评估'_pushtokenManager.default.getDevicePushTokenAsync [react Native Expo]
2020-07-06
5345
无法使用 expo-notifications api 上的 getExpoPushTokenAsync() 函数获取令牌。 下面的函数与 Expo 文档完全相同:
import Constants from "expo-constants";
import * as Notifications from "expo-notifications";
import * as Permissions from "expo-permissions";
async function registerForPushNotificationsAsync() {
let token;
if (Constants.isDevice) {
const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
finalStatus = status;
}
if (finalStatus !== 'granted') {
alert('Failed to get push token for push notification!');
return;
}
token = (await Notifications.getExpoPushTokenAsync()).data;
console.log(token);
} else {
alert('Must use physical device for Push Notifications');
}
if (Platform.OS === 'android') {
Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
});
}
return token;
}
Expo:~37.0.3 App.json:
"expo": {
"android": {
"useNextNotificationsApi": true
}
}
似乎在调用该函数时,收到了下一个警告:
[Unhandled promise rejection: TypeError: undefined is not an object (evaluating '_PushTokenManager.default.getDevicePushTokenAsync')]
3个回答
确保从“expo”导入 {Notifications},而不是从“expo-notifications”导入。 遇到了同样的问题,但后来尝试从“expo”导入,成功了。 查看此图片
Shubham Palkar
2020-07-07
确保您处于托管工作流中,如果您处于裸工作流中,则应指定 { experienceId }。
来自文档的代码示例:
import Constants from 'expo-constants';
import * as Notifications from 'expo-notifications';
export async function registerForPushNotificationsAsync(userId: string) {
let experienceId = undefined;
if (!Constants.manifest) {
// Absence of the manifest means we're in bare workflow
experienceId = '@username/example';
}
const expoPushToken = await Notifications.getExpoPushTokenAsync({
experienceId,
});
await fetch('https://example.com/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
userId,
expoPushToken,
}),
});
}
experienceId (string) - 应将令牌归因于的体验的 ID。默认为 expo-constants 公开的 Constants.manifest.id。在裸工作流中,您必须提供一个采用 @username/projectSlug 形状的值,其中 username 是与项目关联的 Expo 帐户,projectSlug 是来自 app.json 的 slug
更多信息: https://docs.expo.io/versions/latest/sdk/notifications/#dailytriggerinput
kholood
2020-10-25
我有这个错误,因为我没有登录Expo(使用Expo Client)。
jakobinn
2020-11-03