下面添加的代码在 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>
最佳答案
您应该设置初始状态
,就像这样
getInitialState: function(){
return {
data: {
query: {
results: {
channel: {item: {condition: {temp: 0}}}
}
}
}
};
},
Example - (v 0.13.3)
- 注意 - 在版本 0.13.3 中,您应该使用 .render
方法而不是 .renderComponent
或者您可以在 render
方法中检查 data
,如果 data
为 undefined
- 显示 loading ...
。,如果 state
已更新,您将看到您的数据
getInitialState: function(){
return {};
},
render: function() {
if (!this.state.data) {
return <div>Loading...</div>;
}
....
}
关于javascript - 如何在 React js 0.13.3 中访问嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30859390/