反应.js通过数组创建循环
React.js create loop through Array
>我正在尝试显示 10 名玩家的表格。我通过 ajax 获取数据并将其作为道具传递给我的孩子。
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>
);
}
});
现在我需要一个列表组件来渲染玩家:
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>
)
}
});
这给了我一个Uncaught TypeError: Cannot read property 'map' of undefined
.
有点不确定发生了什么,我的控制台日志显示正确的数据,但不知何故我无法在返回中访问它。
我错过了什么?
在组件CurrentGame
您需要更改初始状态,因为您正在尝试使用循环participants
但此属性undefined
这就是您收到错误的原因。
getInitialState: function(){
return {
data: {
participants: []
}
};
},
此外,由于.map
中的player
Object
您应该从中获取属性
this.props.data.participants.map(function(player) {
return <li key={player.championId}>{player.summonerName}</li>
// -------------------^^^^^^^^^^^---------^^^^^^^^^^^^^^
})
Example
正如@Alexander所解决的那样,问题在于异步数据加载 - 您将立即渲染,并且在异步 ajax 调用解析并使用 participants
填充data
之前,您将不会加载参与者。
他们提供的解决方案的替代方案是在参与者存在之前阻止渲染,如下所示:
render: function() {
if (!this.props.data.participants) {
return null;
}
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>
);
}
您可以在执行类似映射之前简单地进行条件检查
{Array.isArray(this.props.data.participants) && this.props.data.participants.map(function(player) {
return <li key={player.championId}>{player.summonerName}</li>
})
}
现在,天.map可以通过两种不同的方式完成,但仍然需要条件检查,例如
.map 带返回
{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => {
return <li key={player.championId}>{player.summonerName}</li>
})
}
.map 不返回
{Array.isArray(this.props.data.participants) && this.props.data.participants.map(player => (
return <li key={player.championId}>{player.summonerName}</li>
))
}
上述两个功能都做同样的事情
相关文章:
- 创建一个循环来简化HTML和CSS代码
- 正在为循环创建唯一id
- 使用来自不同循环Javascript的数据创建数组
- 在for循环中仅创建手风琴的内容
- 在Django中,可以在视图中创建一个包含js的变量,然后在循环模板标记中使用它
- 循环选择标记并创建数组或字符串
- jQuery使用animate创建循环
- 反应.js通过数组创建循环
- 这是否在javascript中创建循环引用
- 为什么要创建循环来获取事件的元素
- 创建循环设置超时 jquery 数组
- jQuery basic:如何使用此结构创建循环
- Javascript:创建循环以连接选中复选框的结果
- 如何基于分隔符从字符串创建循环
- 如何使用two.js创建循环热点
- 正在为setTimeout创建循环
- 在Jquery中使用小数创建循环
- 如何用javascript在carousel中创建循环
- 在 javasctipt 警报或提示中创建循环
- 简单 HTML 表单创建循环中的永恒循环