json - 在带有状态和道具的列表中显示 JSON 对象
问题描述
我正在尝试获取包含有关多个对象的信息的 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')
);
解决方案
道具和状态本质上是两个不同的实体。
- Props 是提供给你的组件的数据
- 状态是组件中定义的数据
查看您的代码,因为它是一个单级组件,所以没有提供任何道具。您应该将代码更改为 -
{this.state.playerList.map(function(players, index) {
return (
<div key={index}>
<h1>{players.age}</h1>
<p>{players.height}</p>
</div>
)})}
假设您的playerList
对象具有age
和height
属性。
希望这能解决:)
推荐阅读
- java - 如何在Android中进行一键登录和注册
- spring-boot - 逗号分隔的请求参数不适用于 Kotlin 数据类
- scala - 如何为自定义错误处理创建自己的解码器?
- c++ - 从 LLVM Kaleidoscope 教程编译代码时遇到问题
- python - 如何在高斯朴素贝叶斯中获得特征重要性
- react-native - 如何实现具有不同颜色的条形图,如 REACT-NATIVE 中的图片所示。帮我解决这个问题
- sql - 递归查询中的 PostgreSQL 顺序
- python - 这种使用 Flask-Login 中的 current_user 的方式安全吗?
- javascript - 将 setState 作为参数传递 Typescript
- drake - 如何使用最新的 pydrake 绑定修复代码?