【发布时间】:2021-09-04 08:14:15
【问题描述】:
如何从 api 将数据存储在异步存储中,然后在 flatList 中显示。 我正在尝试将图像从 api 存储在本地存储中以离线显示
我正在使用以下代码
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://api.flickr.com/services/rest/?method=flickr.photos.getRecent&per_page=20&page=1&api_key=6f102c62f41998d151e5a1b48713cf13&format=json&nojsoncallback=1&extras=url_s')
.then((response) => response.json())
.then((json) => setData(json.photos.photo))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
//将数据值存储到异步字符串jsonValue中
const storeData = async () => {
try {
const jsonValue = JSON.stringify(data)
await AsyncStorage.setItem('@storage_Key', jsonValue)
} catch (e) {
// saving error
}
}
//for retrieving data
const getData = async () => {
try {
const jsonValue = await AsyncStorage.getItem('@storage_Key')
return jsonValue != null ? JSON.parse(jsonValue) : null;
alert(jsonValue)
} catch(e) {
// error reading value
}
}
并使用 flatList 显示它
<FlatList
horizontal={false}
numColumns={3}
data={getData}
renderItem={({ item }) => (
<TouchableOpacity
onPress={() => navigation.navigate("GalleryPhoto",item)}
>
<View style={{flex:1}}>
<Image
source={{ uri: item.url_s }}
style={{ width: 140, height: 140 }}
/>
</View>
</TouchableOpacity>
)}
/>
我没有从 api 获得任何数据
【问题讨论】:
标签: react-native api async-await fetch