【发布时间】: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