2014-11-08 105 views
3

所以我有一個使用的骨幹路由器反應的應用程序,但是當我嘗試在DOMContentLoaded導航,我得到:不變違規:目標容器不是一個DOM元素,當元素在DOM

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 
); 
}; 

LoginForm的組分:

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

路線被命中,按預期擊中- 我錯過了什麼?

這裏是堆棧跟蹤,其底部是我的路由器登入方法:

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 

感謝您的閱讀!

+0

將'console.log(document.getElementById('app-container'))'放在.signIn中,只是爲了檢查。 99%的時間意味着你傳遞了undefined或null作爲第二個參數。 – FakeRainBrigand 2014-11-08 18:24:30

+0

我在檢查後看到類似的問題,因此元素是:) – mattmattmatt 2014-11-08 18:31:44

回答

4

錯誤實際上是從這裏來的在LoginForm的#呈現:

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

這應該是

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

渲染函數應該返回虛擬DOM節點,而不是將它們安裝。由於您使用一個參數調用React.render,因此您明確地得到該錯誤。

+0

呃...哎呀哈哈。我原本不打算在項目中使用'JSX',然後當我決定切換時,我想我完全錯過了......我只覺得有點愚蠢的哈哈。非常感謝! – mattmattmatt 2014-11-08 18:41:12

6

如果React.render中的目標div ID拼寫錯誤,您也可能會收到此錯誤。如果您的index.html包含

<div id="foo"/> 

而呈現呼叫

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

然後目標容器不是一個DOM元素被拋出(注意:酒吧 ID而不是)。

相關問題