【问题标题】:React doesn't show errors in terminal and browserReact 不在终端和浏览器中显示错误
【发布时间】:2023-02-04 21:38:04
【问题描述】:

我用 react-create-app 创建了一个新应用。 这是我的代码:

function App() {
  let m;
  console.log(m); // undefined
  console.log(m.prop); // should throw an error
  return (
    <div className="App">
        App
    </div>
  );
}

我的应用程序编译成功,我只能在 chrome devtools 控制台中看到此错误,但在 IDE 终端或浏览器页面中看不到。浏览器向我显示一个空白页面,我该如何更改此行为?

【问题讨论】:

    标签: compiler-errors create-react-app


    【解决方案1】:

    您可以使用 - try catch -,如果发生某些事情,您可以在浏览器中呈现错误文本。

    例子:

    function App() {
      let m;
      console.log(m); // undefined
      try {
        console.log(m.prop); // should throw an error
      } catch (e) {
        return (<h1>{e.toString()}</h1>);
      }
      return (
        <div className="App">
            App
        </div>
      );
    }
    

    或者

    function App() {
      const [error, setError] = React.useState();
      let m;
      console.log(m); // undefined
      try {
        console.log(m.prop); // should throw an error
      } catch (e) {
        setError(e.toString());
      }
      return (
        <div className="App">
            App
            { error && <h1>{error}</h1> }
        </div>
      );
    }
    

    【讨论】:

    • 谢谢你的回答,但这不是我要找的。我只想配置默认的 create-react-app 错误消息。
    • 我不知道这是否可能,但如果你像示例中那样尝试并捕获顶级组件,我认为是相同的。任何组件的任何错误抛出都将被捕获并像您编程的那样表现,例如在浏览器中显示带有某些样式的错误消息。
    【解决方案2】:

    您的 package.json 应该已经在其中安装了这些包:

    "@testing-library/jest-dom": "^5.16.5", "@testing-library/react": "^13.4.0", "@testing-library/user-event": "^13.5.0", “网络生命体征”:“^2.1.4”,

    在关键的“依赖项”中,还必须添加:

    “eslint配置”:{ “延伸”:[ “反应应用程序”, “反应应用程序/笑话” ] },

    与 package.json 对象的“依赖项”处于同一级别, 然后 npm 安装和 npm 启动。 希望这对那些有这个问题的人有用。 :)

    祝你好运。

    {
      "name": "reactapp",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
        "@testing-library/jest-dom": "^5.16.5",
        "@testing-library/react": "^13.4.0",
        "@testing-library/user-event": "^13.5.0",
        "web-vitals": "^2.1.4",
        "react": "^18.2.0",
        "react-dom": "^18.2.0",
        "react-scripts": "^5.0.1",
      },
      "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test --env=jsdom",
        "eject": "react-scripts eject"
      },
      "eslintConfig": {
        "extends": [
          "react-app",
          "react-app/jest"
        ]
      },
      "browserslist": {
        "production": [
          ">0.2%",
          "not dead",
          "not op_mini all"
        ],
        "development": [
          "last 1 chrome version",
          "last 1 firefox version",
          "last 1 safari version"
        ]
      }
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-03
      • 2013-05-28
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-02
      • 1970-01-01
      相关资源
      最近更新 更多