2015-09-17 123 views
1

我無法在傳遞給子組件的狀態中引用對象和數組的元素。在渲染Reactjs應用程序組件時挖掘狀態

我一直沒能清楚地識別情況之間的差異,當我不能在某些子組件中引用它們。

我錯過了什麼?

組件的示例道具在組件下給出。評論。 在我不能例如參考,current.main.tempcurrent.weather[0].它給出了一個undefined錯誤:

var Current = React.createClass({ 
    render: function() { 
    var current = this.props.current; 
    var dateArray = new Date(current.dt * 1000).toDateString().split(" "); 
    console.log("datearray: ", dateArray[0]); 
    var main = current.main; 
    console.log(main); 
    return (
     <div style={{float: "left", clear:"left"}}> 
     <div style={{float: "left"}}> 
      <div>{dateArray[0]}</div> 
      <div>{dateArray[1]} {dateArray[2]}</div> 
      <div>{dateArray[3]}</div> 
     </div> 
     <div style={{float: "left"}}> 
      <div>current: {JSON.stringify(current)}</div> 
     </div> 
     <div style={{float: "left", clear: "right"}}> 
      <div>{JSON.stringify(current.weather)}</div> 
     </div> 
     </div> 
    ); 
    }, 
}); 
    // {"coord":{"lon":32.85,"lat":39.92},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"base":"cmc stations","main":{"temp":28,"pressure":1018,"humidity":34,"temp_min":28,"temp_max":28},"wind":{"speed":2.1},"clouds":{"all":20},"dt":1442483400,"sys":{"type":1,"id":6022,"message":0.0026,"country":"TR","sunrise":1442460682,"sunset":1442505249},"id":323786,"name":"Ankara","cod":200} 

然而,我可以例如參考,current.main.temp或current.weather [0]:

var Hour = React.createClass({ 
    render: function() { 
    var hour = this.props.hour; // is an object. 
    return (
     <div style={{float: "left"}}> 
     <div>{hour.weather[0].main}</div> 
     <div>{hour.weather[0].description}</div> 
     <div><img src={"http://openweathermap.org/img/w/"+hour.weather[0].icon+".png"} /></div> 
     <div>{hour.main.temp}</div> 
     <div>{hour.main.temp_min}</div> 
     <div>{hour.main.temp_max}</div> 
     <div>{hour.main.humidity}</div> 
     <div>{new Date(hour.dt * 1000).getHours()} o,clock</div> 
     </div> 
    ); 
    } 
}); 
// {"dt":1442437200,"main":{"temp":16.39,"temp_min":14.78,"temp_max":16.39,"pressure":914.76,"sea_level":1026.82,"grnd_level":914.76,"humidity":67,"temp_kf":1.62},"weather":[{"id":800,"main":"Clear","description":"sky is clear","icon":"01n"}],"clouds":{"all":0},"wind":{"speed":1.41,"deg":308.503},"sys":{"pod":"n"},"dt_txt":"2015-09-16 21:00:00"} 

回答

0

這是因爲你的數據結構。

您的天氣數據中沒有任何屬性datacurrent.data.dtcurrent.data.main未定義。

+0

不,我擁有它,只是評論的示例數據是錯誤的。我已糾正它。另外,我可以在我的應用程序引用中提到您提到的'current.data.dt'和'current.data.main'。 –

+0

但是現在我改變了它,因爲它不包含字段數據,並且該組件不引用與數據字段相關的任何內容。 –