我有以下组件,我在其中插入了一些JSON,并尝试使用来获取一些嵌套信息{ this.state.data.items[0]}
,但是出现了错误:Uncaught TypeError: Cannot read property '0' of undefined
,尽管,{this.state.data}
并且也{this.state.data.items}
可以正常工作
这是完整的代码:
var Box = React.createClass({
getInitialState: function () {
return {data: []};
},
loadStuffFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
console.log(data);
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
componentDidMount: function() {
this.loadStuffFromServer();
setInterval(this.loadStuffFromServer, this.props.pollInterval);
},
render: function() {
return (
<div>
{ this.state.data.items[0]}
</div>
);
}
});
你getInitialState
应该看起来像这样
getInitialState: function () {
return {
data: {
items: []
}
};
},
因为。render
之前的调用componentDidMount
,您正在尝试从中获取属性items
,state.data
但该属性不存在
this.state.data // => returns empty Array
那么你正在尝试获得财产 items
this.state.data.items // => returns undefined
因为data
没有财产items
。
然后您尝试从中获取第一个元素,items
Array
但返回了先前的语句undefined
,这就是为什么要获取Error
,因为您无法从undefined
值中获取属性
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句