【问题标题】:How to render data in FlatList in react native, I can Console log it but have a problem to display it on Screen如何在本机反应中渲染 FlatList 中的数据,我可以控制台记录它,但在屏幕上显示它时出现问题
【发布时间】:2021-08-31 16:55:07
【问题描述】:

我想使用异步存储实现 Cashing,但我遇到了这个错误

TypeError: undefined is not an object (evalating 'item.id.toString')

这是我的代码

import React, {useState} from 'react';
import {View, Button, FlatList, Text} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

const books = [
  {id: 1, name: 'book 1'},
  {id: 2, name: 'book 2'},
  {id: 3, name: 'book 3'},
];

export default function GetDataScreen() {
  const [Books, setBooks] = useState([]);
  console.log(Books.length);
  console.log(Books);

  const clearAsyncStorage = async () => {
    AsyncStorage.clear();
  };

  const storeData = async value => {
    try {
      const books = JSON.stringify(value);
      await AsyncStorage.setItem('books', books);
    } catch (e) {
      console.log(e);
    }
  };

  const getData = async () => {
    try {
      const jsonValue = await AsyncStorage.getItem('books');

      setBooks(jsonValue);
      console.log(Books);
      return jsonValue != null ? JSON.parse(jsonValue) : null;
    } catch (e) {
      console.log(e);
    }
  };

  React.useEffect(() => {
    getData();
  }, []);

  return (
    <View>
      <Button title="Save" onPress={() => storeData(books)} />
      <Button title="get" onPress={() => getData()} />
      <FlatList
        data={Books}
        keyExtractor={item => item.id.toString()}
        renderItem={({item}) => <Text>{item.id}</Text>}
      />
    </View>
  );
}

当我评论我的 FlatList 时,我从 Async Storage 获取数据并将其记录在控制台中,

但是当我取消注释 FlatList 时,会出现该错误 " TypeError: undefined is not an object (evalating 'item.id.toString') "

【问题讨论】:

    标签: javascript arrays json react-native asyncstorage


    【解决方案1】:

    您将整个数组存储在 in-store 方法中,当您获取时,您将整个数组作为一个 Item 获取,因此它肯定会给您一个错误。

    您可以按如下所述传递密钥提取器:

      keyExtractor={(item,index) => item.id}
    

    当您从异步获取数据时,您将接收 Item 作为一个

    [ { " 一世 d " : 1 , " n 一种 米 e " : " b ○ ○ k

    1 " } , { " 一世 d " : 2 , " n 一种 米 e " : " b ○ ○ k

    2 " } , { " 一世 d " : 3 , " n 一种 米 e " : " b ○ ○ k

    3 " } ]

    在存储时它应该是单个的,但是您通过按保存按钮来存储整个数组。

    希望你能理解。

    【讨论】:

    • 我明白了,但是出现了一个新的错误,警告:列表中的每个孩子都应该有一个唯一的“关键”道具。检查VirtualizedList的渲染方法。请参阅reactjs.org/link/warning-keys 了解更多信息。 CellRenderer@10.0.2.2:8081/…
    • 是的,您需要为数组中的每个对象提供唯一的键。目前,它正在重复对象的 id,这就是它会给出此错误的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 1970-01-01
    相关资源
    最近更新 更多