简体   繁体   中英

Export an instance to external component with react

I have a configuration component in react and I need to export the instance to another external component, in this case the: const appInstance

export const setupApp = () => {
  if (isAppAvailable) {
    try {
      {...}

      const appConfiguration = new AppConfiguration(KEY);
      AppConfig.configure(appConfiguration);

      // I need to export this const
      const appInstance = AppConfig.start(startInstance);
      
    } catch (e) {
      console.error(e);
    }
  }
};

And in other component, I need to take this instance, like this:

// get app instance from another page
appInstance.get(myTest)
  .then((value) => {
    if (...) {
      something
    } else {
      something;
    }
  });

How can I do this?

Your function setupApp currently has no return value. If you add appInstance to the return, you can access it from outside the function.

export const setupApp = () => {
  if (isAppAvailable) {
    try {
      {...}

      const appConfiguration = new AppConfiguration(APP_KEY);
      AppConfig.configure(appConfiguration);

      // I need to export this const
      const appInstance = AppConfig.start(startInstance);

      return {
          appConfiguration,
          appInstance,
      }
      
    } catch (e) {
      console.error(e);
    }
  }
};
// get app instance from another page
const appInstance = setupApp().appInstance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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