深入研究Reactjs应用组件的渲染状态

Digging into state in render of Reactjs app components

本文关键字:状态 组件 Reactjs 应用 深入研究      更新时间:2023-09-26

不能在传递给子组件的状态下引用对象和数组的元素。

当我不能在某些子组件中引用它们时,我不能清楚地识别它们之间的区别。

我想念的是什么?

组件下面给出了组件的示例道具。评论。因为我不能引用例如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"}

这是因为你的数据结构。

您的天气数据中没有任何称为data的属性,因此current.data.dtcurrent.data.main是未定义的