我一直在尝试让一个数组进入react,然后在浏览器上显示它。数据即将到来,但由于某种原因,我无法显示它。
ReactJs:
import React, { Component } from "react";
export default class RegisterPage extends Component {
constructor(props){
super(props);
this.state = {
};
this.getPlayers();
}
getPlayers() {
fetch('/draft/get-players')
.then((response) => response.json())
.then((data) => {
this.setState({
players: data,
});
});
}
render(){
return (<h1>{this.state.players[0].name}</h1>)
}
}
我最初试图将其映射到多行HTML中,但通过故障排除了解到,我甚至无法从数组中提取一个元素。
JSONfrom/draft/get-players:
[
{
"id": 1,
"name": "Aidan Hutchinson",
"position": "EDGE",
"EstimatedRound": 1,
"college": "Michigan",
"age": "SR",
"TakenRound": null,
"TakenPick": null
},
{
"id": 2,
"name": "Aidan Hutchinson",
"position": "EDGE",
"EstimatedRound": 1,
"college": "Michigan",
"age": "SR",
"TakenRound": null,
"TakenPick": null
},
{
"id": 3,
"name": "Kayvon Thidobeaux",
"position": "EDGE",
"EstimatedRound": 1,
"college": "Oregon",
"age": "SOPH",
"TakenRound": null,
"TakenPick": null
},
{
"id": 4,
"name": "Kyle Hamilton",
"position": "S",
"EstimatedRound": 1,
"college": "Notre Dame",
"age": "JR",
"TakenRound": null,
"TakenPick": null
},
{
"id": 5,
"name": "Ikem Ekwonu",
"position": "OL",
"EstimatedRound": 1,
"college": "NC State",
"age": "SOPH",
"TakenRound": null,
"TakenPick": null
}
]
//您没有声明数组播放器,只需首先初始化数组,它将在中工作
this.state = {
players:[]
}
我发现了这个问题。
该页在提取数据之前就已呈现,因此当呈现该页时,它抛出了一个错误,因为"this.state.players"为空。
我通过创建带有初始渲染的元素来修复这个问题,因为我知道它是空的,但当状态更改时,它会更新为元素。该元素包含JSX,然后将使用我的信息进行呈现。
代码:
import React, { Component } from "react";
export default class RegisterPage extends Component {
constructor(props){
super(props);
this.state = {
players:[],
}
this.getPlayers();
}
getPlayers() {
fetch('/draft/get-players')
.then((response) => response.json())
.then((data) => {
this.setState({
players: data,
});
});
}
render(){
let players = this.state.players.map((player)=>{
return(
<div>
{player.name}
</div>
);
}
);
return (
<div>
{players}
</div>)
}
}
这个SO线程帮助我解决了这个问题。在React组件中动态创建元素