简体   繁体   English

将 JSON 值保存在 Expo React Native 变量中

[英]Save the JSON value in Expo React Native variable

In React Native Expo when the device receives a push notification, there is a JSON that is called "data" that brings with it keys and values.在 React Native Expo 中,当设备收到推送通知时,有一个 JSON 被称为“数据”,它带来了键和值。

Example:例子:

const message = {
  to: YOUR_PUSH_TOKEN,
  sound: 'default',
  title: 'Original Title',
  body: 'And here is the body!',
  data: { name: 'max' },
};

Now, I need to save the value of "name" in a variable but I can't bring it.现在,我需要将“name”的值保存在一个变量中,但我不能带它。 I leave the complete code below.我在下面留下完整的代码。

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>
    );
  }
}

After several tests and errors I came to the conclusion that data has to bring more than one value.经过几次测试和错误,我得出结论,数据必须带来不止一个价值。 Example:例子:

data{
"id":"13456789",
"name":"max"}

Although we are not going to use the id, you need to bring at least two objects.虽然我们不会用到id,但是你至少需要带两个对象。 So now {console.log(notification.data.name)} does work.所以现在{console.log(notification.data.name)}确实有效。

Anyway, I don't think it's the definitive solution, but with me it worked perfect.无论如何,我认为这不是最终的解决方案,但对我来说它很完美。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM