我正在从 API 端点获取 JSON 数据,并希望使用此数据来显示表格。
这是我目前正在尝试的:
var DeliveryOptionsTHeadTh = React.createClass({
render: function() {
return (
<th>{this.props.label}</th>
);
}
});
var DeliveryOptionsTHead = React.createClass({
getInitialState : function(){
return {
data : []
}
},
componentDidMount: function() {
$.get(this.props.source, function(result) {
console.log(result);
this.setState({data: result});
}.bind(this));
},
render: function() {
return (
<thead>
<tr>
<DeliveryOptionsTHeadTh label={this.state.data.days[0].label}/>
</tr>
</thead>
);
}
});
var DeliveryOptionsTable = React.createClass({
render: function() {
return (
<table className='pure-table pure-table-horizontal'>
<DeliveryOptionsTHead source="<REDACTED>" />
<tbody>
</tbody>
</table>
);
}
});
ReactDOM.render(
<DeliveryOptionsTable />,
document.getElementById('example')
)
但这返回Uncaught TypeError: Cannot read property '0' of undefined
。为什么这不起作用?
您需要更改初始状态,如days
are Array
of Objects
你正在尝试render
方法获取第一个元素Array
但在初始状态下没有days
属性,这就是你收到错误的原因
var DeliveryOptionsTHead = React.createClass({
getInitialState : function(){
return {
data: { days: [] }
}
},
componentDidMount: function() {
$.get(this.props.source, function(result) {
this.setState({data: result});
}.bind(this));
},
render: function() {
var days = this.state.data.days.map(function (day) {
return <DeliveryOptionsTHeadTh label={day.label} key={ day.date } />;
});
return <thead>
<tr>{ days }</tr>
</thead>;
}
});
Example http://jsfiddle.net/69z2wepo/26302/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)