![](/img/trans.png)
[英]React Native Expo - Setting an Initial Value Before Variable Assignment
[英]Save the JSON value in Expo React Native variable
在 React Native Expo 中,當設備收到推送通知時,有一個 JSON 被稱為“數據”,它帶來了鍵和值。
例子:
const message = {
to: YOUR_PUSH_TOKEN,
sound: 'default',
title: 'Original Title',
body: 'And here is the body!',
data: { name: 'max' },
};
現在,我需要將“name”的值保存在一個變量中,但我不能帶它。 我在下面留下完整的代碼。
import { Text, View, Button } from 'react-native';
import { Notifications } from 'expo';
import * as Permissions from 'expo-permissions';
import Constants from 'expo-constants';
const YOUR_PUSH_TOKEN = '';
export default class AppContainer extends React.Component {
state = {
notification: {},
};
registerForPushNotificationsAsync = async () => {
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;
}
let token = await Notifications.getExpoPushTokenAsync();
console.log(token);
} else {
alert('Must use physical device for Push Notifications');
}
};
componentDidMount() {
this.registerForPushNotificationsAsync();
// Handle notifications that are received or selected while the app
// is open. If the app was closed and then opened by tapping the
// notification (rather than just tapping the app icon to open it),
// this function will fire on the next tick after the app starts
// with the notification data.
this._notificationSubscription = Notifications.addListener(
this._handleNotification
);
}
_handleNotification = notification => {
this.setState({ notification: notification });
};
// Can use this function below, OR use Expo's Push Notification Tool-> https://expo.io/dashboard/notifications
sendPushNotification = async () => {
const message = {
to: YOUR_PUSH_TOKEN,
sound: 'default',
title: 'Original Title',
body: 'And here is the body!',
data: { name: 'max' },
};
const response = await fetch('https://exp.host/--/api/v2/push/send', {
method: 'POST',
headers: {
Accept: 'application/json',
'Accept-encoding': 'gzip, deflate',
'Content-Type': 'application/json',
},
body: JSON.stringify(message),
});
const data = response._bodyInit;
console.log(`Status & Response ID-> ${JSON.stringify(data)}`);
};
render() {
return (
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'space-around',
}}>
<View style={{ alignItems: 'center', justifyContent: 'center' }}>
<Text>Origin: {this.state.notification.origin}</Text>
<Text>Data: {JSON.stringify(this.state.notification.data)}</Text>
{console.log(notification.data.name)}
</View>
<Button
title={'Press to Send Notification'}
onPress={() => this.sendPushNotification()}
/>
</View>
);
}
}
經過幾次測試和錯誤,我得出結論,數據必須帶來不止一個價值。 例子:
data{
"id":"13456789",
"name":"max"}
雖然我們不會用到id,但是你至少需要帶兩個對象。 所以現在{console.log(notification.data.name)}
確實有效。
無論如何,我認為這不是最終的解決方案,但對我來說它很完美。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.