【问题标题】:React Native Render Modal onMessage Firebase NotificationReact Native Render Modal onMessage Firebase 通知
【发布时间】:2021-04-06 11:24:48
【问题描述】:

我在我的应用程序的服务类(不是 React 组件)中注册了一个 onMessage() Firebase 通知侦听器。

在方法内部,我调用了一个呈现模态的 React 组件。问题是组件永远不会被调用(我尝试在组件的constructor()render() 方法中添加调试语句,但它们没有被打印出来。

这是我的监听代码:

this.notificationListener = messaging().onMessage(async notification => {
    console.log("listener is invoked"); //this is printed.
    <MyModalComponent />
}

根据 Riwen 的评论更新了 Class 代码:

class NotificationService extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
           dummy: false,
        }
    }

    render() {
        return(<></>);
    }

    async registerNotifications() {
        await this.checkPermissions();

        this.registerNotificationsListeners();
    }

    registerNotificationsListeners() {
        this.notificationListener = messaging().onMessage(async notification => {
            console.log('there is a notification ', notification); //this gets printed
            this.setState({dummy: true});
            {this.state.dummy && <MyModalComponent />}
        }
    }
}

<NotificationService />

组件仍未被调用。

【问题讨论】:

  • 从组件监听事件,设置触发时的状态,当状态改变时显示模态。
  • 谢谢。我刚刚将我的类转换为组件,但仍未调用它,请参阅编辑后的帖子。

标签: javascript firebase react-native ecmascript-6


【解决方案1】:

试试这个:

class NotificationService extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
           dummy: false,
        }
    }

    render() {
        return(<>{this.state.dummy && <MyModalComponent />}</>);
    }

    registerNotificationsListeners() {
        this.notificationListener = messaging().onMessage(async notification => {
            console.log('there is a notification ', notification); //this gets printed
            this.setState({dummy: true});
        }
    }
}

还要确保您确实注册了通知侦听器,例如在componentDidMount

【讨论】:

  • 谢谢。现在我得到了这个:ERROR: Can't call setState on a component that is not yet mounted,即使我在该文件的末尾有 &lt;NotificationService /&gt;(假设它应该在 App.js 中加载文件时挂载)。
  • @codebee 你在哪里打电话给registerNotificationsListeners
  • NotiticationService.registerNotifications() 内,请查看更新后的代码。然后我在 App.js 中调用该方法 -> await NotificationService.registerNotifications();
  • @codebee 在安装组件之前,您不应该尝试修改状态。相反,您应该只在适当的生命周期方法中注册任何事件(大多数情况下,componentDidMount)。理想情况下,您还应该在卸载之前取消订阅,以避免出现与您提到的相同的错误。
猜你喜欢
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多