如何在 React Native 组件周围传递全局 object?

How to pass a global object around React Native components?

我正在尝试在我的 React Native 应用程序中设置一个消息传递模块,它应该从服务获取信息并以不同的方式在不同的组件中呈现它。有点像这里的收件箱消息:您收到一条消息,在 header 组件中,您会看到带有红点的收件箱和新消息的数量。如果单击它,您将转到另一个完全呈现消息的组件。

现在,我创建了两个组件来以这两种不同的方式呈现收件箱。但是当我尝试 link 它们到处理通知的 class 时,我在组件 class 内部收到错误,说 object 未定义。

我有这样的东西:

Class 存储新消息

class Notifications {
    constructor() {
        this.notifications = [];
    }

    receiveNotification(notif) {
        this.notifications.push(notif);
    }
}

let notifications = new Notifications();

export { notifications };

Class 处理来自服务的新消息

import framework from 'framework'; // this is the framework I use to communicate with the service
import Notifications from './Notifications.js';

export class PushNotificator extends Component {
  constructor(props) {
    super(props);
    this.state = {
      token: ""
    }
  }

  componentDidMount() {
    framework.requestPermissions()
    .then(() => console.log('granted'))
    .catch(() => console.log('notification permission rejected'));


    framework.getToken().then(token => {
      console.log("TOKEN (getToken)", token);
      this.setState({token: token});
    });

    this.notificationListener = framework.on(frameworkEvent.Notification, notif => {
      console.log("Notification", notif);
      this.showLocalNotification(notif);
    })
  }

  showLocalNotification(notif) {
    Notifications.notifications.push(notif); // this fails because Notifications is undefined
    framework.presentLocalNotification({
      title: notif.title,
      body: notif.body,
      priority: "high",
      click_action: notif.click_action,
      show_in_foreground: true,
      local: true
    });
  }

  componentWillUnmount() {
    this.notificationListener.remove();
  }


  render() {
    return null;
  }
}

header收件箱组件的相关部分

import Notifications from './Notifications.js' //assume the paths are correct 
import {PushNotificator} from './PushNotificator.js'

export class Home extends Component {
    constructor(props) {
        super(props);

        this.state = {
            loading: true,
            notifications: Notifications.notifications.find(notif => notif.seen).length
        };

        this.closeActivityIndicator = () => setTimeout(() => {
            this.setState({ loading: false });
        }, 2000);
    }

...
render() {
    <PushNotificator />
    ...
}

一调用构造函数,程序就失败了,因为通知是未定义的。但为什么它是未定义的?不能这样用吗?

谢谢。

我知道有两个选项可以解决您的问题:

1. 您已经实例化了您的 Notifications,因此可以默认导出该实例而无需额外包装:

export default notifications;

然后只是:

import notifications from './Notifications.js';
// ...
notifications.push(notif); 

2. 如果您不想使用 default,您可以继续通过

导出您的实例
export { notifications };

在这种情况下,您需要正确导入它:

import { notifications } from './Notifications.js';
// ...
notifications.push(notif); 

但是在这两种情况下,您都在使用实例化的 notifications 对象,而不是 Notifications class.