【问题标题】:how to add data from api to async storage in react-native如何在 react-native 中将数据从 api 添加到异步存储
【发布时间】: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


    【解决方案1】:

    尝试将data={getData} 替换为data={this.getData}

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案2】:

    您可以像这样在 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} />
    

    【讨论】:

    • 如何传递这个 obj 和密钥 .... 用于在平面列表中显示 ...你能写出你的答案,它会输出类似数据数组的东西吗?@Manish Mahajan
    • @AdiruvSingh 答案已更新,现在根据您的要求使用它。
    猜你喜欢
    • 1970-01-01
    • 2022-01-01
    • 2021-12-13
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    相关资源
    最近更新 更多