不能访问React对象状态上的object属性,即使它存在.返回未定义

Can't access object property on a React object state, even though it exists. Returns undefined

本文关键字:存在 未定义 返回 属性 object React 访问 对象 状态 不能      更新时间:2023-09-26

我使用AJAX来获取一些JSON,然后我想显示值。如果我退出包含我想要显示的值的对象,我可以看到键和值。但是,当我试图直接访问该值时,得到undefined

这是我卡住的组件:

var WeatherCard = React.createClass({
  getInitialState: function () {
    return {};
  },
  componentDidMount: function() {
    var comp = this;
    $.get("http://api.openweathermap.org/data/2.5/weather?zip=" +  this.props.zipcode + ",us", function(data) {
    comp.setState(data);
  });
 },
 render: function() {
    // I want to get the value @ this.state.main.temp
    // this works...
    console.log(this.state.main);
    // this does not work...
    // console.log(this.state.main.temp);
    // I want "current temp" to display this.state.main.temp
    return (
        <div className="well">
          <h3>{this.state.name}</h3>
          <p>Current Temp: {this.state.main} </p>
          <p>Zipcode: {this.props.zipcode}</p>
        </div>
     );
    }
});

这是整块的。
http://plnkr.co/edit/oo0RgYOzvitDiEw5UuS8?p=info

在第一次传递时,this.state为空,这将使this.state.main.temp为未定义。要么用正确的结构化对象预填充状态,要么用if子句包装。

对于返回null或未定义的对象,React将直接跳过渲染,没有任何警告或错误,但是当你有返回null或未定义的嵌套结构时,会使用正常的JavaScript行为。

尝试使用main: [], data:[]来设置初始状态,而不是使用空对象。

我有同样的问题,一旦我把我的AJAX setState和做了一个空的初始状态,一切都开始正常工作。

我是React的新手,所以我不能给你一个很好的解释为什么这会产生不同。我似乎遇到了各种各样奇怪的问题。

希望有帮助。