以下添加的代码在React js 0.10.0中正常工作。我想在0.13.0版本中运行相同的代码。我的主要要求是访问嵌套对象作为默认对象,如“this.state.data.query.results.channel.item.condition.temp”。
<!doctype html>
<html>
<head>
<title>Weather Widget</title>
<link rel="stylesheet" href="weather.css" />
<script src="http://fb.me/react-0.10.0.js"></script>
<script src="http://fb.me/JSXTransformer-0.10.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<script type="text/jsx">
/*** @jsx React.DOM */
var weatherWidget = React.createClass({
loadData: function(){
$.ajax({
url: 'http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%2222102%22&format=json',
dataType : "jsonp",
cache: false,
success: function(data) {
console.log(data)
this.setState({data: data});
}.bind(this)
});
},
getInitialState: function(){
return {data: []};
},
componentWillMount: function(){
this.loadData();
},
render: function(){
return(
<div className="ww-container">
<div className="ww-current-condition">
<div className="ww-current-temperture">{this.state.data.query.results.channel.item.condition.temp}°</div>
</div>
</div>
)
}
});
React.renderComponent(<weatherWidget />, document.body);
</script>
</body>
</html>
答案 0 :(得分:2)
你应该 set initial state
,就像这样
getInitialState: function(){
return {
data: {
query: {
results: {
channel: {item: {condition: {temp: 0}}}
}
}
}
};
},
Example - (v 0.13.3)
- 注意 - 在版本 0.13.3 中,您应该使用.render
方法而不是.renderComponent
或者您可以使用data
方法检查render
,如果data
是undefined
- 则显示loading...
。如果state
已更新,则可以会看到你的data
getInitialState: function(){
return {};
},
render: function() {
if (!this.state.data) {
return <div>Loading...</div>;
}
....
}