简体   繁体   English

反应本机FlatList对象显示

[英]React Native FlatList Object displaying

I have the below object that I am retrieving from the AsyncStorage, and I want to display it in a FlatList but I am getting the following error: 我有要从AsyncStorage检索的以下对象,我想在FlatList显示它,但出现以下错误:

Invariant Violation: Invariant Violation: Invariant Violation: Invariant Violation: Tried to get frame for out of range index NaN 不变违规:不变违规:不变违规:不变违规:试图获取超出范围索引NaN的帧

My JSON format is: 我的JSON格式是:

Object {
  "44": Object {
    "pro_id": "44",
    "pro_img": "url",
    "pro_name": " S4 ",
  },
  "52": Object {
    "pro_id": "52",
    "pro_img": "url",
    "pro_name": " S4 ",

  },
}

The JSON above is retrieved from AsyncStorage like so: 上面的JSON是从AsyncStorage检索的, AsyncStorage所示:

retrieveData = async () => {

    try {
       await AsyncStorage.getItem('userFavorites')
       .then(req => JSON.parse(req))
       .then(json => this.setState({ favPro:json }))

    } catch (error) {

    } 
}

My method for rendering items in the FlatList is defined like this: 我在FlatList渲染项目的FlatList是这样定义的:

 fav = ({ item }) => {
    return (
      <View>
      <Text>{item.pro_id+ item.pro_name}</Text>
      </View>
    )
}

Finally, I render the FlatList as follows: 最后,我将FlatList呈现如下:

<FlatList
          data={this.state.favPro}
          renderItem={this.fav}
          keyExtractor={item => item.pro_id}
        />

How I can display my JSON data using the FlatList component? 如何使用FlatList组件显示JSON数据?

The FlatList component expects an array input for the data prop. FlatList组件需要用于data FlatList的数组输入。 Based on your JSON format, it appears you're passing in an object rather than an array. 根据您的JSON格式,您似乎正在传递一个对象而不是数组。

Consider the following adjustment to your render method: 考虑对渲染方法进行以下调整:

// Convert object to array based on it's values. If favPro not 
// valid (ie during network request, default to an empty array)
const data = this.state.favPro ? Object.values(this.state.favPro) : []

<FlatList
  data={data}
  renderItem={this.fav}
  keyExtractor={item => item.pro_id}
/>

You're using async / await incorrectly. 您正在使用async / await不正确。 Instead of calling .then you assign your call to await to a variable (or don't assign it if it does not return a value) and wrap the call (or calls) to await in a try / catch block. 而不是调用.then ,然后将要await的调用分配给一个变量(如果不返回值,则不要分配它),然后将一个(或多个)调用包装在try / catch块中以await The await keyword will automatically handle resolve and reject so you get the appropriate information. await关键字将自动处理resolvereject因此您可以获得适当的信息。

retrieveData = async () => {
  try {
    const data = JSON.parse(await AsyncStorage.getItem("userFavorites"))
    this.setState({ favPro: data })
  } catch (error) {
    console.error(error)
    this.setState({ favPro: [] })
  }
}

You also need to pass an array, the shape of your data looks like an object, but it should be an array of objects. 您还需要传递一个数组,数据的形状看起来像一个对象,但是它应该是一个对象数组。 This is not a terribly difficult transformation and I can provide a helper function if you need it. 这并不是一个非常困难的转换,如果需要,我可以提供一个辅助功能。

edit: if you need to convert an object into an array, you can use the reduce function 编辑:如果需要将对象转换为数组,可以使用reduce函数

const data = {
  '44': { a: 2 },
  '55': { b: 3 },
}

const dataArr = Object.keys(data).reduce(
  (arr, key) => arr.concat(data[key]),
  []
)

By using Object.keys we can each object by name. 通过使用Object.keys我们可以按名称命名每个对象。 Then call reduce and the array returned by Object.keys , passing a function as the first argument, and an empty array as the second argument. 然后调用reduce并由Object.keys返回数组,将函数作为第一个参数,并将空数组作为第二个参数。 The second argument is automatically passed to the function as the first argument, arr , and the second argument of the function we pass is the key of the object. 第二个参数作为第一个参数arr自动传递给函数,而我们传递的函数的第二个参数是对象的键。 Then it's just a matter of adding the objects to the array using concat . 然后,只需使用concat将对象添加到数组即可。

Array.reduce can seem a little overwhelming at first but it's a very powerful method and you can get a lot done with it. Array.reduce乍一看似乎有点让人不知所措,但这是一个非常强大的方法,您可以完成很多工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM