【问题标题】:Export an instance to external component with react使用反应将实例导出到外部组件
【发布时间】:2021-05-26 12:35:53
【问题描述】:

我在 react 中有一个配置组件,我需要将实例导出到另一个外部组件,在这种情况下是: 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);
    }
  }
};

在其他组件中,我需要使用这个实例,如下所示:

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

我该怎么做?

【问题讨论】:

  • 你可以提供的是顶级上下文提供者
  • 你能更好地解释一下我该怎么做吗?

标签: javascript reactjs constants


【解决方案1】:

您的函数setupApp 目前没有返回值。如果在返回值中添加appInstance,则可以从函数外部访问它。

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

【讨论】:

  • 我尝试了这个解决方案,但是我不能使用返回,在 es-lint 中会出现这个错误 -- 期望在箭头函数的末尾返回一个值
猜你喜欢
  • 2020-10-23
  • 2017-08-24
  • 1970-01-01
  • 2017-07-06
  • 2014-12-23
  • 2016-01-13
  • 2023-03-11
相关资源
最近更新 更多