我在这里阅读过OneSignal安装:https://documentation.onesignal.com/docs/react-native-sdk-setup#step-5---initialize-the-onesignal-sdk。该文档以组件类样式编写。
如何在React Native应用程序的无状态功能组件中添加OneSignal?
我尝试使用useEffect,但OneSignal仍然无法检测到我的应用。
谢谢。
答案 0 :(得分:0)
我通过在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.
答案 1 :(得分:0)
享受
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 (
...
);
};