【发布时间】:2019-12-16 19:46:59
【问题描述】:
我正在尝试在 React Native Flatlist 中显示来自 Steam API 的游戏信息。我是 React 和 JSX 的新手,所以我读到的很多内容都没有意义。
我希望平面列表显示特定帐户拥有的游戏名称列表。从 Steam 的 API 调用(通过 fetch)返回的数据如下所示:
{
"response": {
"game_count": 69,
"games": [
{
"appid": 220,
"name": "Half-Life 2",
"playtime_forever": 24,
"img_icon_url": "fcfb366051782b8ebf2aa297f3b746395858cb62",
"img_logo_url": "e4ad9cf1b7dc8475c1118625daf9abd4bdcbcad0",
"has_community_visible_stats": true,
"playtime_windows_forever": 0,
"playtime_mac_forever": 0,
"playtime_linux_forever": 0
},
{
"appid": 320,
"name": "Half-Life 2: Deathmatch",
"playtime_forever": 0,
"img_icon_url": "795e85364189511f4990861b578084deef086cb1",
"img_logo_url": "6dd9f66771300f2252d411e50739a1ceae9e5b30",
"has_community_visible_stats": true,
"playtime_windows_forever": 0,
"playtime_mac_forever": 0,
"playtime_linux_forever": 0
},
等等。因为我试图按名称显示游戏列表,所以 name 属性是我唯一需要的。
数据将每个游戏列为匿名对象,因此我无法像往常一样使用点符号访问每个游戏中的属性。我尝试使用 for 循环遍历它们,但这也不起作用。根据我的研究,似乎人们通常将 Array.map 用于此类事情,但我不清楚它是否可以与 Objects 一起使用。
我遇到的另一个问题是 Flatlist keyExtractor 属性。我知道它应该是一个匿名函数,它返回有关每个 Flatlist 项目的一些唯一索引或属性,目的是使结构更有效并允许它跟踪列表的更新。但是,我不知道如何自己创建此功能。我认为 JSON 数据中的 appid 字段将是一个不错的候选者,但我不确定如何将其放入 keyExtractor 函数中。
所以,把它作为一个问题:我将如何显示来自包含平面列表中匿名子对象的 JSON 对象的数据,以及如何使用不同的数据条目填充该列表的 keyExtractor (该列表中的appid?
下面是我的起始代码:
import React, {Component} from 'react';
import {FlatList, Stylesheet, Text, View} from 'react-native';
export default class App extends Component {
state = {
dataset: []
};
componentWillMount() {
this.fetchData();
}
fetchData = async () => {
const response = await fetch("<API URL>");
const json = await response.json();
//const data = json.map((item) => item.games.name);
var key = 0;
const data = json[games][0][name];
this.setState({ dataset: data });
}
render() {
console.log(this.state.dataset);
return (
<View>
<FlatList
data={this.state.dataset}
keyExtractor={(x, i) => i} //I have no idea what this does, or if it makes sense here.
//Where do x and i come from? (I got this from a tutorial video
//and this was glossed over)
renderItem={({ item }) => //Where does item come from?
<Text>
{item}
</Text>
}
/>
</View>
);
}
}
【问题讨论】:
标签: json react-native react-native-flatlist