javascript - 带子项的 JSON 解析器
问题描述
我有这个 Json 文件:
{
"id":0,
"leagueCaption":"League Two",
"rankings":[
{
"id":0,
"position":1,
"teamName":"Portsmouth",
"wins":26,
"draws":9,
"losses":11,
"points":87
},
{
"id":0,
"position":2,
"teamName":"Plymouth Argyle",
"wins":26,
"draws":9,
"losses":11,
"points":87
},
{
"id":0,
"position":3,
"teamName":"Doncaster Rovers FC",
"wins":25,
"draws":10,
"losses":11,
"points":85
}
]
}
我正在尝试使用地图渲染列表,但是我无法通过子排名来渲染它,我需要将leaguecaption 渲染为标题,以及网格上的排名,
我这样做了,但它仍然无法正常工作,它返回一个错误,说无法渲染,
我的请求:
getItems(event) {
event.preventDefault();
this.setState({ 'isLoading': true });
API.getRanking(this.state.code)
.then(items => this.setState({ items, 'isLoading': false }))
.catch(error => this.setState({ error, isLoading: false }));
}
我的组件:
render() {
return (
<div>
<table className="pure-table">
<thead>
<tr>
<th className="itemGrid">Position</th>
<th className="itemGrid">Points</th>
<th className="itemGrid">Name</th>
<th className="itemGrid">Wins</th>
<th className="itemGrid">Draws</th>
<th className="itemGrid">Defeats</th>
</tr>
</thead>
<tbody>
{
this.props.items.map(function (team) {
return (
<tr key={team.id}>
<td>{team.position}</td>
<td>{team.points}</td>
<td>{team.teamName}</td>
<td>{team.wins}</td>
<td>{team.draws}</td>
<td>{team.losses}</td>
</tr>
);
})
}
</tbody>
</table>
</div>
)
}
我的屏幕渲染:
return (
<div className="container" >
<div className="header">
<h1>Championship of Football</h1>
</div>
<ChampionshipForm
onSubmit={this.getItems}
controlId='form'
id="code"
name="code"
value={this.state.code}
onChange={this.setCode.bind(this)}
/>
<RankingTable items={this.state.items}/>
</div>
);
错误信息:
解决方案
你的问题不是很清楚。但我怀疑您正在访问项目之前可用。尝试在您的组件中添加如下所示的简单检查
{
this.props.items && this.props.items.map(function (team) {
return (
<tr key={team.id}>
<td>{team.position}</td>
<td>{team.points}</td>
<td>{team.teamName}</td>
<td>{team.wins}</td>
<td>{team.draws}</td>
<td>{team.losses}</td>
</tr>
);
})
}
另一种可能的方案是,items
不是数组,因此items.map
不是函数的原因。你可以在你的组件中进行控制台this.props.items
,它的类型如下
console.log(this.props.items);
console.log(typeof this.props.items)
上面的第二个控制台应该打印数组。如果不是,那么您传递的项目类型错误。
我注意到的另一件事。您的数组是rankings
并且 items 是您上面的 json 中的一个对象。考虑改变
<RankingTable items={this.state.items}/>
至
<RankingTable items={this.state.items.rankings}/>
推荐阅读
- java - 我需要一个正则表达式来使用 java 进行名称验证
- python - asyncio call_soon 和 call_soon_threadsafe 的区别?为什么 call_soon 线程不安全?
- flutter - 颤振颤振_inappwebview“onEnterFullscreen”
- excel - 在每个空行之后复制每个数据的第一行
- excel - 在 vb.net 中验证 excel 中的字符串
- kdb - 如何在 kdb 中动态计算相关性
- java - Java每秒更改一次JLabel
- python - 根据名称 python 更改类的属性并进行附加验证
- javascript - 如何在同一个 React 中使用多个表单?
- android - 在 Jetpack Compose 中设置焦点顺序的最简单方法是什么?