React Native - как инициализировать OneSignal в компоненте функции без сохранения состояния?

Я прочитал установку OneSignal здесь: https://documentation.onesignal.com/docs/react-native-sdk-setup#step-5---initialize-the-onesignal-sdk. Документация написана в стиле классов компонентов.

Как добавить OneSignal в компонент функции без сохранения состояния в приложении React Native?

Я пробовал использовать useEffect, но OneSignal по-прежнему не может обнаружить мое приложение.

Спасибо.


person fxbayuanggara    schedule 28.06.2020    source источник
comment
Вам когда-нибудь удавалось заставить это работать?   -  person Nick    schedule 29.07.2020
comment
@Nick Да, конечно, я добавил ответ ниже.   -  person fxbayuanggara    schedule 03.08.2020


Ответы (2)


Я получил это сработало, добавив эти строки в App.js:

import OneSignal from 'react-native-onesignal';
...
...
const App = () => {
...

onIds = (device) => {
        if (state.playerId) {
            OneSignal.removeEventListener('ids', onIds);
            return;
        } else {
            setState({ ...state, playerId: device.userId });
            console.log('Device info: ', state.playerId);
        }
    };



OneSignal.addEventListener('ids', onIds);
...
}

И в index.js:

import OneSignal from 'react-native-onesignal'; // Import package from node modules




OneSignal.setLogLevel(6, 0);

// Replace 'YOUR_ONESIGNAL_APP_ID' with your OneSignal App ID.
OneSignal.init(YOUR_ONESIGNAL_APP_ID, {
    kOSSettingsKeyAutoPrompt: false,
    kOSSettingsKeyInAppLaunchURL: false,
    kOSSettingsKeyInFocusDisplayOption: 2
});
OneSignal.inFocusDisplaying(2); // Controls what should happen if a notification is received while the app is open. 2 means that the notification will go directly to the device's notification center.
person fxbayuanggara    schedule 03.08.2020
comment
Вы не используете хук useEffect? - person Stiven Castillo; 05.11.2020

Наслаждаться

import OneSignal from 'react-native-onesignal';

const SplashScreen = () => {
  useEffect(() => {
    OneSignal.setLogLevel(6, 0);
    OneSignal.init('Your-id-app', {
      kOSSettingsKeyAutoPrompt: false,
      kOSSettingsKeyInAppLaunchURL: false,
      kOSSettingsKeyInFocusDisplayOption: 2,
    });
    OneSignal.inFocusDisplaying(2);

    OneSignal.addEventListener('received', onReceived);
    OneSignal.addEventListener('opened', onOpened);
    OneSignal.addEventListener('ids', onIds);

    return () => {
      OneSignal.removeEventListener('received', onReceived);
      OneSignal.removeEventListener('opened', onOpened);
      OneSignal.removeEventListener('ids', onIds);
    };
  }, []);

  const onReceived = (notification) => {
    console.log('Notification received: ', notification);
  };

  const onOpened = (openResult) => {
    console.log('Message: ', openResult.notification.payload.body);
    console.log('Data: ', openResult.notification.payload.additionalData);
    console.log('isActive: ', openResult.notification.isAppInFocus);
    console.log('openResult: ', openResult);
  };

  const onIds = (device) => {
    console.log('Device info: ', device);
  };

  return (
    ...
  );
};
person Stiven Castillo    schedule 05.11.2020