2015-07-03 32 views
0

我有兩個類,officerModalsOfficerPhoto,並且officerModals應該將數據傳遞到OfficerPhoto。但是,當我嘗試註銷OfficerPhoto中的數據時,我只能得到undefined。我一直在關注Reacts的教程,我不知道我可能出錯的地方。誰能幫忙?ReactJS this.props.data是undefined

reactReady = -> 
    officerModals = React.createClass 
     getInitialState: -> 
      {data: []} 
     componentDidMount: ->    
      $.ajax 
       url: this.props.url 
       dataType: 'json' 
       cache: false 
       success:((data) -> 
        @setState data: data 
        # console.log data <- this logs the correct data 
        console.log @state.data.officers <- so does this 
       ).bind(this) 
     render: -> 
      React.createElement 'div', { className: 'photos' }, React.createElement(OfficerPhoto, data: @state.data.officers) 

    OfficerPhoto = React.createClass     
     render: ->    
      React.createElement 'h1', {className: 'yes'} 
     console.log 'test'          
     console.log @props #<- this returns undefined 

    React.render React.createElement(officerModals, {url: "officers.json"}), $('#officerPics').get 0 

$(document).ready reactReady 
$(document).on 'page:load', reactReady 

編輯:我被困在一個字符串我登錄@props權利之前,我註釋掉@state.data.officers。看來OfficerPhoto是在officerModals之前渲染的 - 我該如何解決這個問題?

回答

0

這看起來像種族條件。您的ajax查詢在render方法運行之前不會返回,因此state.data.officers未定義。

+0

但他有setState方法,它會在數據到達時再次重新渲染。我想是這樣。 –

+0

使用chrome調試器並在transpilled代碼上設置一些標記以查看它失敗的位置。第一站是在ajax承諾解決後檢查狀態。 – gor181

+0

在我登錄@props之前,我卡在一個隨機字符串中,看起來像是在officerModals之前正在運行圖片。我將如何去解決這個問題? – Andrew

0

問題是officeModals不通過OfficerPhoto上的道具。也許使用Object.assign將解決你的問題:

React.createElement(OfficerPhoto, Object.assign({}, this.props, { data: 'values' })); 
+0

我嘗試了你的建議,但不幸的是它沒有奏效 – Andrew