不变冲突:当元素在DOM中时,目标容器不是DOM元素

Invariant Violation: Target container is not a DOM element, when element is in the DOM

本文关键字:元素 DOM 目标 冲突 中时      更新时间:2023-09-26

所以我有一个使用主干路由器的react应用程序,但当我尝试在DOMContentLoaded上导航时,我得到:

Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element. 

我尝试过遍历堆栈跟踪,但不知道发生了什么,因为抛出错误的方法(ReactMount._registerComponent)被命中了几次,前两次没有抛出错误,因为有问题的DOM元素就在那里。我正在使用我在其他项目中使用过的组件,没有问题,并且已经将所有部分剥离到最低限度来调试(到目前为止没有成功):

DOM结构:

<html>
    <head>
    </head>
    <body>
        <div id="app-container">
        </div>
        <script src="http://fb.me/react-with-addons-0.12.0.js"></script>
        <script type="text/javascript" src="js/application.js"></script>
    </body>
</html>

带有路由器代码:

AppRouter.prototype.signIn = function () {
  var container = document.getElementById( 'app-container' );
  React.render(
    <LoginForm />,
    container
  );
};

登录表单组件:

var LoginForm = React.createClass({
  render: function () {
    return(
      React.render(
        <div id="login-form-component">
        </div>
      )
    );
  },
});

路线被击中,LoginForm#render如预期被击中——我错过了什么?

这是堆栈跟踪,其底部是我的路由器签名方法:

invariant 
ReactMount._registerComponent 
(anonymous function) 
ReactPerf.measure.wrapper 
ReactMount.render 
ReactPerf.measure.wrapper 
React.createClass.render 
(anonymous function) 
ReactPerf.measure.wrapper
(anonymous function)
ReactPerf.measure.wrapper
ReactComponent.Mixin._mountComponentIntoNode
Mixin.perform 
ReactComponent.Mixin.mountComponentIntoNode
(anonymous function)
ReactPerf.measure.wrapper
ReactMount.render 
ReactPerf.measure.wrapper
AppRouter.signin

感谢阅读!

如果React.render中的目标div id拼写错误,也可能会出现此错误。如果您的index.html包含

<div id="foo"/>

而呈现调用是

React.render(React.createElement(App, null), document.getElementById("bar"));

目标容器不是DOM元素被抛出(注意barid而不是foo)。

错误实际上来自LoginForm#render:

return(
  React.render(
    <div id="login-form-component">
    </div>
  )
);

那应该是

return(
    <div id="login-form-component">
    </div>
);

render函数应该返回虚拟dom节点,而不是装载它们。您之所以会出现错误,是因为您使用一个参数调用React.render。