我试图获取一个json文件与几个对象的信息,但我似乎无法正确。我很反应,所以我可能会混淆这个,状态和道具,或其他东西。
我已成功从控制台的json中收到对象列表,但我无法在return语句中显示它们。
感谢您的帮助!
import React from 'react';
import ReactDOM from 'react-dom';
class PlayerFeed extends React.Component {
constructor(props) {
super(props);
this.state = {
'playerList': []
};
}
componentDidMount() {
this.getPlayers();
}
getPlayers() {
fetch('http://link.to/json/players/')
.then(results => results.json())
.then(results => console.log(results))
.then(results => this.setState({'playerList': results}));
}
render() {
return (
<ul>
{this.props.state.map(function(players, index) {
return (
<div key={index}>
<h1>{this.props.age}</h1>
<p>{this.props.height}</p>
</div>
)
}
)}
</ul>
);
}
}
ReactDOM.render(
<PlayerFeed />,
document.getElementById('root')
);
道具和州基本上是两个不同的实体。
查看您的代码,因为它是一个单级组件,所以没有提供任何道具。您应该将代码更改为 -
{this.state.playerList.map(function(players, index) {
return (
<div key={index}>
<h1>{players.age}</h1>
<p>{players.height}</p>
</div>
)})}
假设你的playerList
对象有age
和height
属性。
希望这解决:)
我认为你应该在状态而不是道具中循环播放列表。道具是从父组件获得的。
render() {
return (
<ul>
{
for(var player of this.state.playerList) {
return (
<div key={player.index}>
<h1>{player.age}</h1>
<p>{player.height}</p>
</div>)
}
}
</ul>
);
}
此外,您可以在chrome中安装react develop插件,以查看状态和道具中的值。