我正在尝试在React.js前端显示来自本地API的数据。
它显示一个只有表头的空表,但表上没有条目。JSON从API中通过,就好像I console.log(this.state.cards),它在命令行上记录数组。
如有任何帮助,我们不胜感激!
谢谢!
import React, { Component } from 'react';
import '../css/card.css';
import Card from './Card';
import CardTable from './CardTable.js';
import request from 'request';
class TopCards extends Component {
constructor() {
super();
this.state = {
cards: [],
};
}
componentDidMount() {
const url = "http://localhost:1200";
request({
url: url,
json: true
}, (error, response, body) => {
if (!error && response.statusCode === 200) {
for (let i in body) {
this.state.cards.push(body[i]);
}
}
})
}
render() {
if(this.state.cards) {
var cardList = this.state.cards.map(function(card){
return(
<CardTable key={card.cardName} card={card} />
);
});
}
return (
<div className="TopCards">
<h1>Top Cards This Week:</h1>
<br />
<table width="400">
<tr>
<th>Name</th>
<th>Count</th>
<th>Wins</th>
<th>Losses</th>
<th>Win %</th>
</tr>
{cardList}
</table>
</div>
)
}
}
export default TopCards;
发布于 2018-06-05 05:50:18
你需要用setState
来通知React你想要渲染的事实。其次,你应该确保使用不可变的数据结构。push
或unshift
不会通知任何更改。
for (let i in body) {
this.setState({
cards: [
...this.state.cards,
body[i]
]
});
}
https://stackoverflow.com/questions/50689184
复制相似问题