首页 > 解决方案 > 如何在 react-native 中将数据从 api 添加到异步存储

问题描述

如何从 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-nativeapiasync-awaitfetch

解决方案


您可以像这样在 AsyncStorage 中设置数据:

const storeData = (obj) => {
    return Promise.map(Object.keys(obj), (key) =>
        AsyncStorage.setItem(key, obj[key]),
    ).catch(()=>{});
};

storeData 将返回承诺。

上述函数的输入将是 JSON:

{
    flickerdata:[],
    otherdata:[],
}

数组数据将存储为flickerDataotherdata键。

在以下函数中使用此键从 asyncStore 检索数据:

const retrieveData = (key) => {
    return AsyncStorage.getItem(key).catch(()=>{});
};

在 FlatList 中使用此函数返回的数据

<FlatList data={data} {...otherProps} />

推荐阅读