【问题标题】:React Native and FlatList : Tried to get frame for out of range index NaNReact Native 和 FlatList:试图获取超出范围索引 NaN 的框架
【发布时间】:2019-09-24 20:17:57
【问题描述】:

我是 React Native 的初学者。我有一个变量this.state.forums 有这个值:

{
    "7": {
        "id": 7,
        "wording": "Loisirs, vie sociale et débats"
    },
    "3": {
        "id": 3,
        "wording": "Forums"
    }
}

但是当我写的时候:

<FlatList
    data={this.state.forums}
    renderItem={({ item }) => <Item title={item.wording} />}
    keyExtractor={item => item.id.toString()}
/>

我有这个错误:

Invariant Violation: Invariant Violation: 试图获取超出范围索引 NaN 的帧

你能帮帮我吗?

你知道如何在 keyExtractor 中分​​配密钥(不是item.id)吗?

【问题讨论】:

  • 你确定你提供给 FlatList 的数据在 FlatList 被渲染之前就已经存在了吗?顺便说一句,对于第二个问题,如果这是你想要的,你可以做 keyExtractor = {(item, index) =&gt; index.toString()}
  • 非常感谢第二个问题。是的,并且 this.state.forums 在构造函数this.state = {forums: []} 在http请求之前被初始化。
  • 我在想什么,从你提供的第一个代码块开始。它看起来像这样[{7: ..., 3:...}],如果是这样,你需要删除外部{},然后它看起来像这样:[7: ..., 3:...],告诉我它是否解决了你的问题,然后我会写有更好解释的答案

标签: javascript react-native react-native-flatlist


【解决方案1】:

FlatList 想要它的数据是数组的形式。你给它一个对象。获取 Object.values,你会很好。像data={Object.values(this.state.forums)} 甚至更好,将状态中的论坛存储为数组。

【讨论】:

    【解决方案2】:

    试试这个:-

    // for of
    for (let userObject of this.state.forums) {
    console.log(userObject.wording); // here you can render your views
    }
    
    // map function works for array
    this.state.forums.map((userData) => { 
    return(
    console.log(userData); // render your view
     userData.map((data) => {
      <Text>{data.wording}</Text>
     })
    )
    });
    

    参考链接:-React Native foreach loop

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-04
      • 1970-01-01
      • 2018-07-21
      • 2019-06-30
      • 2020-05-24
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      相关资源
      最近更新 更多