我需要使用React Native中的平面列表来显示Steam API数据的帮助

问题描述 投票:1回答:1

我正在尝试在React Native Flatlist中显示Steam API中的游戏信息。我是React和JSX的新手,所以我读的很多书都没有意义。

我希望Flatlist显示特定帐户拥有的游戏标题的列表。从Steam的API调用(通过提取)返回的数据如下所示:

{
"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函数。

因此,作为一个问题:我将如何在Flatlist中显示包含匿名子对象的JSON对象中的数据,以及如何用其他数据条目填充该列表的keyExtractorappidfrom the list?

下面是我的起始代码:

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
1个回答
1
投票

[好吧,您似乎在理解FlatList的工作方式时遇到了一些小问题。让我为您分解一下。

让我们从Steam API请求开始。在您的示例中,您首先要在状态下将dataset声明为空数组,然后尝试使用网络请求的结果来更新它。问题是,当您执行json['games'][0]['name']时,您正在访问games数组的第一项(索引0)并获取其name property,然后将该名称设置为您的dataset。尽管您忘记了属性名称周围的引号,但是它不起作用。相反,您需要做的是这样:

fetchAllGames = async () => {
    const steamResponse = await fetch("<API URL>");
    const json = await steamResponse.json();

    // We get all the games back from Steam in the form of an array
    this.setState({ games : json.games });
}

我们现在正在使用games数组中的数据正确更新状态内的数组。

让我们继续进行keyExtractorrenderItem功能。 keyExtractor函数用于告知React每个列表项的唯一标识符。在这种情况下,这将是游戏的appid属性。然后,React使用此唯一的ID来区分项目,并确定哪些项目需要更新。此功能为您提供两个参数,即实际项目及其索引。使用这些,我们可以执行以下操作:

keyExtractor = (item, index) => {
    return item.appid.toString();
}

我们现在以字符串形式返回appid属性(这是React期望的键类型)。

renderItem函数有点不同,React为您提供了一个参数,其中包含您的商品以及许多其他属性。由于我们只对实际项目感兴趣,因此我们使用如下方括号来对其进行销毁:{ item }。这是JavaScript中常用的从对象“提取”属性的技术。通常这样使用:

const testObj = {
    name : "John",
    surname : "Doe"
}

const { name, surname } = testObj; 

这样,您可以直接引用namesurname,就好像它们是独立变量一样。另一种方法是:

const testObj = {
    name : "John",
    surname : "Doe"
}

const name = testObj.name;
const surname = testObj.surname;

我希望这可以消除您可能一直在问自己的一些问题!这是下面的完整工作代码。您可能会注意到,我将一些内联函数移到了类成员上,这只是性能优化,以防止在每个渲染器上重新创建该函数,您可以忽略它。

import React, { Component } from 'react';
import { FlatList, Text } from 'react-native';

export default class App extends Component {

    state = {
        games : []
    };

    componentDidMount() {
        this.fetchAllGames();
    }

    fetchAllGames = async () => {
        const steamResponse = await fetch("<API URL>");
        const json = await steamResponse.json();

        // We get all the games back from Steam in the form of an array
        this.setState({ games : json.response.games });
    }

    keyExtractor = (item, index) => {
        return item.appid.toString();
    }

    renderItem = ({item}) => {
        return (
            <Text>{item.name}</Text>
        );
    }

    render() {
        return (
            <FlatList 
                data={this.state.games}
                keyExtractor={this.keyExtractor}
                renderItem={this.renderItem} />
        );
    }
}

编辑#1-正如OP所指出的,我做了一个错字并纠正了它。我还更改了JSON对象以反映response属性。

© www.soinside.com 2019 - 2024. All rights reserved.