【问题标题】:How to import ErrorUtils in React Native如何在 React Native 中导入 ErrorUtils
【发布时间】:2021-08-16 15:03:06
【问题描述】:
  • RN 版本:0.50
  • 在 Android 上测试,尚未在 iOS 上测试

我正在尝试使用ErrorUtils.setGlobalHandler,如此 github 问题中所述:https://github.com/facebook/react-native/issues/1194

但是,问题中不清楚的是如何导入 ErrorUtils。它不在反应文档中:https://facebook.github.io/react-native/docs/0.50/getting-started.html

以前,在 RN 0.41 中,我可以使用 import ErrorUtils from "ErrorUtils"; 导入 ErrorUtils 但是,在 0.50 中,当我尝试像这样导入 ErrorUtils 时,我会收到一个红色的反应弹出窗口,并显示以下消息:

com.facebook.react.common.JavascriptException: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'http://localhost:8081/index.bundle?platform=android&dev=true&minify=false' failed to load.

我也尝试过import { ErrorUtils } from 'react-native';,但那里似乎不存在。错误是:

Cannot read property 'setGlobalHandler' of undefined

如何在 RN 0.50 中正确导入 ErrorUtils?

【问题讨论】:

    标签: react-native


    【解决方案1】:

    ErrorUtils 是一个全局变量,因此不需要导入。您可以使用console.log(global.ErrorUtils) 验证这一点

    但是无论如何它都作为模块导出(here)。那里的评论还提供了更多信息,为什么要这样做。

    你可以像这样导入模块:

    import ErrorUtils from 'ErrorUtils';

    【讨论】:

    • 我在根组件中导入 import React, { ErrorUtils } from 'react'; 并没有收到错误,但根根本不会呈现。从导入中删除 , { ErrorUtils } 使其呈现:shrug:
    【解决方案2】:

    对于 RN61+ 上的任何人,您不应再导入该模块,因为您将在运行 Metro bundler 中遇到以下错误:

    Error: Unable to resolve module `ErrorUtils`
    

    相反,只需使用模块而不导入,因为这是一个全局变量,如 leo 所述

    【讨论】:

      【解决方案3】:

      我确实创建了一个 global.d.ts 来定义一个全局变量,

      interface Global {
      
         ErrorUtils: {
            setGlobalHandler: any
            reportFatalError: any
            getGlobalHandler: any
         }
      
      }
      
      declare var global: Global
      

      然后,在您尝试使用它的地方,只需

      global.ErrorUtils.setGlobalHandler(xxxx)
      

      【讨论】:

        猜你喜欢
        • 2021-09-01
        • 1970-01-01
        • 2018-08-12
        • 1970-01-01
        • 2018-07-21
        • 2017-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多