React Native: 如何在点击推送通知时调用一个函数?

4
当用户点击推送通知时, 我希望能将用户引导至特定的导航场景。而这个“场景”和“ID”已在 JSON 格式的通知负载中传递。
但是我不知道该如何在代码中使用这些值。
PushNotificationIOS.addEventListener('notification', this._onNotification.bind(this));

"通知"事件。

当点击通知时,应用程序显然会出现,但我该如何在出现后触发一个函数?

谢谢!

1个回答

1
在你的最上层组件中,即在 index.ios.js 中注册的组件中,在 componentDidMount 方法中,你可以添加监听器并从通知中 获取数据
export default class App extends Component {
    componentDidMount() {
        PushNotificationIOS.addEventListener('notification', this._onNotification.bind(this));
        if (notification) {
            const data = notification.getData();
            if (data) {
                // do your thing
            }
        }
    }
}

另一种解决方案是传递一个URL,并在您的最顶层组件的componentDidMount方法中实现以下代码:
Linking.getInitialURL().then(url => {
  if (!url) {
    return null;
  }
  // do something to decide which component to load
  navigator.push({
    component: YourComponent,
    passProps: {
      // your props
    },
  });
  return null;
}).catch(() => null);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接