对React native和它的概念来说是相当新的.我已经使用RN创建了一个应用程序,从中获取API数据

http://jsonplaceholder.typicode.com/photos

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

如果你能在此基础上给我提供帮助/建议,那就太好了.我已经在我的应用程序中包含了两个重要文件的源代码,以及一个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;

以及与GalleryList关联的GalleryDetail-

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;

我的try 方法是-

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);
  }
}

React-native相关问答推荐

Redux将旧状态迁移到新状态

Reaction-Native-pdf文件不是PDF格式或已损坏

莫迪德不会停留在屏幕中央

expo 使用错误的版本代码创建建筑

使用动画标记时如何优化react 本机 map 性能

在向后滑动时执行操作(react-navigation )

Javascript setTimeout 立即在 React Native 中运行

如何运行 React-Native 示例?

React-native 在浏览器中打开链接并返回应用程序

因 JVM 堆空间耗尽而导致守护进程到期?

如何将参数传递给graphql片段?

React Native 中的全屏图像

Error when running watchman

java.lang.ClassNotFoundException:在路径上找不到类.MainActivity:DexPathList react-native

在 Docker 中使用 Fastlane 构建 iOS 应用

如何在 React Native 上获取设备的 ip?

如何将 Crashlytics 与 React Native 应用程序集成

React Native - Firebase 身份验证持久性不起作用

在 React-Native 中手动设置 opacity 的 onPress of TouchableOpacity 的音量

React Native 模块中的依赖注入