React Uncaught Error:目标容器不是DOM元素[重复]

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React Uncaught Error:目标容器不是DOM元素[重复]相关的知识,希望对你有一定的参考价值。

我最近创建了我的webpack配置文件:

const path = require("path");

const SRC_DIR = path.join(__dirname, "/client/src");
const DIST_DIR = path.join(__dirname, "/client/dist");

module.exports = {
  entry: `${SRC_DIR}/index.jsx`,
  output: {
    filename: "bundle.js",
    path: DIST_DIR
  },
  module: {
    rules: [
      {
        test: /.jsx?$/,
        include: SRC_DIR,
        exclude: /node_modules/,
        loader: "babel-loader",
        query: {
          presets: ["react", "es2015"]
        }
      }
    ]
  },
  mode: "development"
};

这个很好,并捆绑了jsx文件:

import React from "react";
import ReactDOM from "react-dom";

class MainApp extends React.Component {
  render() {
    return (
      <div className="content">
        <h1>Hello World</h1>
      </div>
    );
  }
}

ReactDOM.render(<MainApp />, document.getElementById("app"));

现在在html文件中我包含了带有div id应用程序的bundle文件。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>REACT TEST</title>
  <script src="./bundle.js"></script>
</head>

<body>
  <div id="app"></div>
</body>

</html>

当我试图运行它似乎它不起作用,我得到错误:

Uncaught Error: Target container is not a DOM element.
    at invariant (invariant.js:42)
    at legacyRenderSubtreeIntoContainer (react-dom.development.js:17116)
    at Object.render (react-dom.development.js:17195)
    at eval (index.jsx:48)
    at Object../client/src/index.jsx (bundle.js:97)
    at __webpack_require__ (bundle.js:20)
    at bundle.js:84
    at bundle.js:87
invariant   @   invariant.js:42

我在这里错过了什么?为什么我收到此错误?

答案

你有它的方式它甚至在你拥有DOM之前运行。

你应该把它包含在底部,如下所示:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>REACT TEST</title>
</head>

<body>
  <div id="app"></div>
  <script src="./bundle.js"></script>
</body>

</html>
另一答案

您在容器初始化之前插入React脚本。像这样:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>REACT TEST</title>
</head>

<body>
  <div id="app"></div>
  <script src="./bundle.js"></script>
</body>

</html>

以上是关于React Uncaught Error:目标容器不是DOM元素[重复]的主要内容,如果未能解决你的问题,请参考以下文章

React-Slick Slider Giving Error “Uncaught TypeError: Cannot call a class as a function”

React 13.3 unmountComponentAtNode() 错误:目标容器不是 DOM 元素

React Native: Uncaught (in promise) 错误: DeltaPatcher 在初始化时应该收到一个基础 Bundle

反应简单代码错误:目标容器不是DOM元素

ERROR 错误:未捕获(承诺中):MyPlugin 没有 Web 实现

react(81)--没有正确引入导出错误