I'm using AJAX to get some JSON, and then I want to display the value. If I log out he object that contains the value I want to display, I can see the key and the value. However, when I try to access the value directly, I get undefined.
Here is the ponent that I am stuck on:
var WeatherCard = React.createClass({
getInitialState: function () {
return {};
},
ponentDidMount: function() {
var p = this;
$.get(".5/weather?zip=" + this.props.zipcode + ",us", function(data) {
p.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>
);
}
});
Here is the whole plunk.
I'm using AJAX to get some JSON, and then I want to display the value. If I log out he object that contains the value I want to display, I can see the key and the value. However, when I try to access the value directly, I get undefined.
Here is the ponent that I am stuck on:
var WeatherCard = React.createClass({
getInitialState: function () {
return {};
},
ponentDidMount: function() {
var p = this;
$.get("http://api.openweathermap/data/2.5/weather?zip=" + this.props.zipcode + ",us", function(data) {
p.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>
);
}
});
Here is the whole plunk.
http://plnkr.co/edit/oo0RgYOzvitDiEw5UuS8?p=info
2 Answers
Reset to default 6On first pass, this.state
is empty which will render this.state.main.temp
as undefined. Either you prefill the state with a correct structured object or wrap in if
clauses.
For objects that returns null or undefined React will simply skip rendering it without any warnings or errors, however when you have nested structures that return null or undefined normal JavaScript behaviour is employed.
Try setting your initial state using main: [], data: [] rather than an empty object.
I was having the same problems and once I took my AJAX setState and made an empty initial state everything started working fine.
I'm new to React so I can't give you a very good explanation as to why this made a difference. I seem to stumble into all kinds of strange problems.
Hope this helped.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745171740a4614966.html
评论列表(0条)