Хуки могут быть вызваны только внутри тела компонента функции - PullRequest
0 голосов
/ 11 марта 2020

Я пытаюсь реализовать Уведомление Firebase в моем приложении RN. Я следовал за этим постом

Но когда я запускаю код, я получаю Hooks can only be called inside the body of a function component. Там есть мое приложение. json file

export default class App extends Component {
  state = {
  isLoadingComplete: false,
};

  render() {
     return (
       <SafeAreaView forceInset={{ bottom: 'never'}} style={styles.container}>
         {Platform.OS === 'ios' && <StatusBar barStyle="default" />}
         <Provider store={store}>
         <AppNavigator/>
         </Provider>
       </SafeAreaView>
     );
  }

и функции для получения токена, разрешений и показа оповещений при удаленном уведомлении. Эти функции в правильном месте?

  useEffect(() => {
    this.checkPermission();
    this.messageListener();
   }, []);

   checkPermission = async () => {
    const enabled = await firebase.messaging().hasPermission();
    if (enabled) {
      this.getFcmToken();
    } else {
      this.requestPermission();
    }
   }

   getFcmToken = async () => {
    const fcmToken = await firebase.messaging().getToken();
    if (fcmToken) {
     console.log(fcmToken);
     this.showAlert("Your Firebase Token is:", fcmToken);
    } else {
     this.showAlert("Failed", "No token received");
    }
   }

   requestPermission = async () => {
    try {
     await firebase.messaging().requestPermission();
     // User has authorised
    } catch (error) {
      // User has rejected permissions
    }
   }

   messageListener = async () => {
    this.notificationListener = firebase.notifications().onNotification((notification) => {
      const { title, body } = notification;
      this.showAlert(title, body);
    });

    this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
      const { title, body } = notificationOpen.notification;
      this.showAlert(title, body);
    });

    const notificationOpen = await firebase.notifications().getInitialNotification();
    if (notificationOpen) {
      const { title, body } = notificationOpen.notification;
      this.showAlert(title, body);
    }

    this.messageListener = firebase.messaging().onMessage((message) => {
     console.log(JSON.stringify(message));
    });
   }

   showAlert = (title, message) => {
    Alert.alert(
     title,
     message,
     [
      {text: "OK", onPress: () => console.log("OK Pressed")},
     ],
     {cancelable: false},
    );
   }
}

Понятия не имею, что мне не хватает. Может быть, какая-то функция выходит за рамки ... Но я не могу понять

1 Ответ

0 голосов
/ 11 марта 2020

Я изменил useEffect на componentDidMount(), и он прекрасно работал

componentDidMount() {
  this.checkPermission();
  this.messageListener();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...