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

时间:2017-12-31 11:06:18

标签: android reactjs caching react-native redux

React原生及其概念相当新。我已经和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));



        }
    }

提前致谢!

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:2)

来自Subramanya的方法基本上就是您需要开始使用的方法,我只是要介绍一种使用redux-persist的状态管理方法,您可以在应用程序增长时欣赏它。< / p>

  

Redux Persist性能高,易于实施且易于扩展。

假设您已将您的应用与redux相关联并实施了一个相当有条理的状态树,redux-persist将整个应用状态存储为AsyncStorage或您选择的任何存储引擎。< / p>

例如,假设您的API端点返回了一组照片,您只需更新商店,您的用户就可以确保他们的数据安全并使用redux-persist保存。

我没有测试下面的所有代码

首先定义store

import { AsyncStorage } from 'react-native';
import { createStore, compose, applyMiddleware, } from "redux";
import { persistStore } from "redux-persist";
import ReduxThunk from "redux-thunk";

import reducers from "../reducers"

const middleWare = [ReduxThunk]

const store = createStore(
  reducers, 
  {},
  compose(applyMiddleware(...middleWare))
)

// you can define more parameters, like blacklist or whitelist a reducer
// also, specify storage engine
persistStore(store, { storage: AsyncStorage });

export default store;

在您应用的入口点

import React, { Component } from "react";
import { Provider } from "react-redux";
import Router from "./Router";
import store from './store';

export default class App extends Component {

  constructor(props) {
    super(props);
  }

  render() {
    return (
      <Provider store={store}>
        <Router />  // navigator
      </Provider>
    );
  }
}

最后,你的API逻辑。

// action creator
export storePhoto = photos => {
    return {
        type: 'STORE_PHOTOS',
        payload: photos
    }
}

// photos reducer
import { REHYDRATE } from 'redux-persist/constants';

export default (state = {}, action) => {
  switch (action.type) {
    case STORE_PHOTOS:
      return { ...state, photos: action.payload }
  // this is where `redux-persist` handles caching
    case REHYDRATE:
      var incoming = action.payload;
      if(incoming) return { ...state, ...incoming }
      return state;
    default:
      return state;
  }
};

要检索数据,您会看到redux抽象出所有多余的逻辑,并且不再有setItem, getItem,因为redux-persist会为您自己做到这一点。

import { connect } from "react-redux";
import { storePhotos } from "./actions";

class GalleryList extends Component {

    async componentDidMount() {
        const photos = await axios.get('http://jsonplaceholder.typicode.com/photos');
        storePhoto(photos)
    }

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

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

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

// pull data from photos reducer
const mapStateToProps = ({ photos }) => {
    return {
        photos: photos.photos
    }
}

export default connect(mapStateToProps, { storePhotos })(GalleryList);

总结一下,

  1. 在项目中安装redux-persist。
  2. 导入persistStore和autoRehydrate表单redux-persist。
  3. 将autoRehydrate添加到商店。
  4. 将您的商店传递给persistStore。
  5. 听取reducer上的persist / REHYDRATE操作并相应地填充状态。
  6. 希望我的回答有所帮助!