2015-03-25 40 views
0

我有一個ReactJS成分,我想安裝到#test-scoresuser/show.html compontent。 組件住在app/assets/javascripts/react-components/test-score.js.jsx只有載荷時某些頁面上有反應護欄

我怎樣才能確保它只是加載當用戶訪問user/show? 它加載的每一頁,因爲它是現在。

應用程序/資產/ Javascript角/反應-components.js:

//= require_tree ./react-components 

應用程序/資產/ Javascript角/反應組分/測試score.js.jsx

1 $(document).ready(function() { 
    2 
    3 var TestResultBox = React.createClass({ 
    4  loadTestScoreFromServer: function() { 
    5  $.ajax({ 
    [snipp...] 
74 React.render(
75  <TestResultBox />, 
76  document.getElementById('test-scores') 
77 ); 

這導致一個JS錯誤,打破其他東西:

react.js?body=1:20238 Uncaught Error: Invariant Violation: 
_registerComponent(...): Target container is not a DOM element. 

到我如何組織的事情有什麼建議? :-)

乾杯, 馬丁

回答

0

這是一個「很好的錯誤」,因爲它讓你知道你嘗試訪問它之前的節點不在DOM存在的。您可以輕鬆地檢查節點首先存在,是這樣的:

var scores = document.getElementById('test-scores') 
if (scores) { 
    React.render(<TestResultBox />, scores); 
} 

的jQuery有silenting錯誤的壞習慣,但如果你想使用jQuery來代替,像這樣的工作:

$('#test-scores').each(function() { 
    React.render(<TestResultBox />, this); 
}) 
+0

謝謝,就是這樣! :-) – martins 2015-03-25 13:51:15