React.js创建通过数组循环
问题描述:
我想显示一个表的10名球员。我从通过AJAX获取数据,并把它作为道具,我的孩子。
I'm trying to display a Table of 10 Players. I get the data from via ajax and pass it as props to my Child.
var CurrentGame = React.createClass({
// get game info
loadGameData: function() {
$.ajax({
url: '/example.json',
dataType: 'json',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error('#GET Error', status, err.toString());
}.bind(this)
});
},
getInitialState: function(){
return {data: []};
},
componentDidMount: function() {
this.loadGameData();
},
render: function() {
return (
<div className="CurrentGame">
<h1> Current Game Information</h1>
<PlayerList data={this.state.data}/>
</div>
);
}
});
现在我需要一个List组件渲染玩家:
Now I need a List Component to Render the Players:
var PlayerList = React.createClass({
render: function() {
// This prints the correct data
console.log(this.props.data);
return (
<ul className="PlayerList">
// I'm the Player List {this.props.data}
// <Player author="The Mini John" />
{
this.props.data.participants.map(function(player) {
return <li key={player}>{player}</li>
})
}
</ul>
)
}
});
这给了我一个未捕获的类型错误:无法读取的特性图未定义
我有点不确定发生了什么,我的控制台日志显示正确的数据,但不知何故,我不能访问它的回报。
I'm kind of unsure what is happening, my console log displays the correct data but somehow I can't access it in the return.
我在想什么?
答
试试这个
getInitialState: function(){
return {data: {participants: []}};
},
更新
this.props.data.participants.map(function(player) {
return <li key={player.championId}>{player.summonerName}</li>
})