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

Posted

技术标签:

【中文标题】将 JSON 值保存在 Expo React Native 变量中【英文标题】:Save the JSON value in Expo React Native variable 【发布时间】:2019-11-08 21:20:03 【问题描述】:

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


【问题讨论】:

欢迎来到***。由于这里的大多数人都说英语,即使是错误信息,您能翻译一下您的标题吗? console.log(notification.data.name) 你的意思是这个拿不到吗? 不,console.log(notification.data.name) 它不起作用,也许我遥不可及,但我不知道如何恢复该值 【参考方案1】:

经过多次测试和错误,我得出结论,数据必须带来不止一个价值。示例:

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

虽然我们不会用到id,但你至少需要带两个对象。所以现在 console.log(notification.data.name) 确实有效。

无论如何,我认为这不是最终的解决方案,但对我来说效果很好。

【讨论】:

以上是关于将 JSON 值保存在 Expo React Native 变量中的主要内容,如果未能解决你的问题,请参考以下文章

无法让 Jest expo 应用程序与 react-navigation 一起使用

从使用 Expo SDK 构建的 React-Native 应用程序将照片分享到 Instagram

Google Play Expo w/ React - Expo 的 app.json 文件中与 Android 对应的 plist 是啥?

加载前启动画面白色闪烁(React Native Expo)

firestore 不适用于 React Native Expo

React Native / Expo:Fetch 抛出“网络请求失败”