简体   繁体   English

在 useEffect 之外只调用一次函数反应原生

[英]calling a function only one time outside of useEffect react native

I have a function for setting up push notifications which needs to be called one time after the user logs in. This has to be outside of useEffect because the documentation says so.我有一个设置推送通知的功能,需要在用户登录后调用一次。这必须在 useEffect 之外,因为文档是这样说的。

I tried calling it in the component which comes after the user logs in, but the function is called 3 times after app is opened from killed state.我尝试在用户登录后的组件中调用它,但是在从终止状态打开应用程序后,该函数被调用了 3 次。 Is there a way to limit this call to only one?有没有办法将此调用限制为一个?

Here is the code so far:这是到目前为止的代码:

const HomeScreen: FC<Props> = ({navigation}) => {

  setupPushNotifications();

    return (
    <SafeAreaView style={homeStyles.wrapper}>
      <Header navigation={navigation} />
      <View style={homeStyles.container}>
...
...

One way to do it would have been to use constructor in react classes, but the whole application is written in ES6 and relies too much on hooks.一种方法是在 react 类中使用构造函数,但是整个应用程序是用 ES6 编写的,并且过于依赖钩子。

Is there any other way i can make this work?还有其他方法可以使这项工作吗?

You can call this in your main file index.js in root directory of your project您可以在项目根目录的主文件 index.js 中调用它

import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

setupPushNotifications();

AppRegistry.registerComponent(appName, () => App);

But you said you want to call it only if user is logged in then in the same file where you placed setupPushNotifications just update the position of it and move it out side class block.但是您说您只想在用户登录时调用它,然后在您放置 setupPushNotifications 的同一文件中更新它的位置并将其移出类块。

setupPushNotifications();

const HomeScreen: FC<Props> = ({navigation}) => {
   ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM