gpt4 book ai didi

android - 如何使用 AsyncStorage React Native 缓存 API 数据

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:48:02 27 4
gpt4 key购买 nike

对 React Native 及其概念相当陌生。我已经使用 RN 玩了一段时间,以创建一个从

获取 API 数据的应用程序

http://jsonplaceholder.typicode.com/photos

我一直在研究 AsyncStorage 的文档以实现如何缓存 API 数据,以便在终止应用程序时,它不必一次又一次地处理从 Web 获取数据,但没有成功能够实现它。

如果你能根据它给我提供帮助/建议就太好了。我在我的应用程序中包含了 2 个重要文件的源代码,以及一个包含我如何尝试实现的 Test.js 文件。

import React, {Component} from 'react';
import { FlatList, View, Text, AsyncStorage, ActivityIndicator } from 'react-native';
import axios from 'axios';
import GalleryDetail from './GalleryDetail';

class GalleryList extends Component {

state = { photos: []};

componentDidMount() {
axios.get('http://jsonplaceholder.typicode.com/photos')
.then(response => this.setState({ photos: response.data }))
.catch((error)=> console.warn("fetch Error: ", error));
}

getPhotos = async()=> {
try {
photos = await AsyncStorage.getItem('GalleryPhotos');
}
catch (error) {
console.error(error);
}
}

savePhotos(){
AsyncStorage.setItem('GalleryPhotos', this.state.photos);
console.log('works !');
}

renderPhoto = ({item})=> {
return <GalleryDetail photo={item}/>
}

keyExtractor = (photo, index) => photo.id;

render () {

if(!this.state.photos){
return <ActivityIndicator/>;
}

return (
<FlatList
data = {this.state.photos}
keyExtractor={this.keyExtractor}
renderItem={this.renderPhoto}
/>
);
}
}

export default GalleryList;

和 GalleryDetail 链接到 GalleryList-

import React, {Component} from 'react';
import { Text, View, Image } from 'react-native';
import Card from './Card';
import CardSection from './CardSection';

const GalleryDetail = (props)=> {
return (
<Card>
<CardSection style = {styles.headerContentStyle}>
<Image
style={styles.thumbnailStyle}
source = {{ uri: props.photo.thumbnailUrl}}/>
<Text style= {styles.textStyle}>{props.photo.title} </Text>
</CardSection>
</Card>
);
};

const styles = {
headerContentStyle: {
flexDirection: 'column',
justifyContent: 'space-around'
},

thumbnailStyle: {
height: 60,
width: 60
},

textStyle: {
fontSize: 12,
//textAlign: 'right',
flexDirection: 'row',
justifyContent: 'flex-end',
flex: 1,
flexWrap: 'wrap',
marginLeft: 5,
marginRight: 5,
}
}

export default GalleryDetail;

我尝试的方法是——启动应用程序后,它将首先在 asyncStorage 中查找,如果它找到数据 - 它会从异步中获取,否则会转到 web,再次获取并存储以备后用。我试图在一个单独的文件中实现类似这样的功能,因为我想分解我已经运行的应用程序。奇怪的破语法是

State = {
photos: []
}

componentDidMount() {

// just a variable acting to fetch data from the stored keyvalue pair

check = AsyncStorage.getItem("PhotosKey").then((response) => {
this.setState({"PhotosKey": response});
}).done();

if(check) {
console.log('Data was fetched!!!!!');
check();
}

else {
console.log("Data was not fetched!");

var Data = axios.get('http://jsonplaceholder.typicode.com/photos').
then(response => this.setState({ photos: response.data })).
catch((error)=> console.warn("fetch Error: ", error));



}
}

提前致谢!

最佳答案

async componentDidMount() {
const photoStorage = await AsyncStorage.getItem('GalleryPhotos')
if(photoStorage) {
try {
const photoResp = await axios.get('http://jsonplaceholder.typicode.com/photos')
const photoData = await JSON.stringify(photoResp.data)
await AsyncStorage.setItem('GalleryPhotos', photoData);
} catch(e) {
console.warn("fetch Error: ", error)
}
.then(response => this.setState({ photos: response.data }))
}
}

稍后

getPhotos = async()=> {
try {
photos = JSON.parse(await AsyncStorage.getItem('GalleryPhotos'));
}
catch (error) {
console.error(error);
}
}

关于android - 如何使用 AsyncStorage React Native 缓存 API 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48041928/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com