【问题标题】:React Native - Retrieve everything in AsyncStorage except keys?React Native - 检索 AsyncStorage 中除键之外的所有内容?
【发布时间】:2018-01-16 17:58:45
【问题描述】:

目前,我正在使用 AsyncStorage.setItem() 将带有字符串化 JSON 对象的字符串键推送到 AsyncStorage。 IE:

当我使用 getAllKeys() 和 multiGet() 检索 AsyncStorage 中的所有内容时,我意识到我只想访问对象本身而没有使用密钥。

我只访问字符串化对象的最有效方法是什么?我当前的函数,其中 element 表示键和值:

importData = () => {
  AsyncStorage.getAllKeys().then(keys => AsyncStorage.multiGet(keys)
    .then((result) => {
      result.map(req => req.forEach((element) => {
        this.setState({ favorites: JSON.parse(element) });
        console.log(this.state.favorites);
      }));
    }));
}

【问题讨论】:

    标签: javascript json react-native foreach asyncstorage


    【解决方案1】:

    这应该会为您提供除键之外的所有值。如果您的数据在层次结构中,您会想要JSON.parse()

      getData = async () => {
        try {
          await AsyncStorage.getAllKeys().then(async keys => {
            await AsyncStorage.multiGet(keys).then(key => {
              key.forEach(data => {
                console.log(data[1]); //values
              });
            });
          });
        } catch (error) {
          Alert.alert("Couldn't load data", error);
        }
      };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-29
      • 2018-06-20
      • 1970-01-01
      • 2012-08-01
      • 2019-11-03
      • 1970-01-01
      相关资源
      最近更新 更多