AsyncStorage 删除项目不起作用

AsyncStorage remove item is not working

我设法在 asyncStorage 中存储和操作项目,但现在我试图在按下按钮时删除特定项目。

这是代码:

import React, { Component } from "react";
import {
  StyleSheet,
  Text,
  View,
  Image,
  ScrollView,
  FlatList,
  Button,
  AsyncStorage
} from "react-native";
import ajax from "./ajax.js";
import PropTypes from "prop-types";
import InspirationList from "./InspirationList";
import FavoriteItem from "./FavoriteItem";
import ProductItem from "./ProductItem";

class Favorites extends Component {
  state = {
    favorites: []
  };

  componentDidMount() {
    this.showProduct();
  }

  async showProduct() {
    let k = 0;
    AsyncStorage.getAllKeys().then(keys =>
      AsyncStorage.multiGet(keys).then(result => {
        let res = [];
        result.map(req => {
          req.forEach(element => {
            k++;
            if (element != null && k % 2 == 0) {
              res.push(JSON.parse(element));
            }
          });
          this.setState({ favorites: res });
        });
        console.log(this.state.favorites);
      })
    );
  }

  async removeItemValue(favi) {
    AsyncStorage.getAllKeys().then(keys =>
      AsyncStorage.multiGet(keys).then(result => {
        result.map(req => {
          req.forEach(element => {
            if (element === JSON.stringify(favi)) {
              AsyncStorage.removeItem(element);
              console.log("they are the same");
            }
          });
        });
      })
    );
  }

  //AsyncStorage.removeItem(element);

  render() {
    return (
      <ScrollView style="styles.fav">
        {this.state.favorites.map(fav => (
          <View key={fav.key}>
            <Text>{fav.nume}</Text>
            <Image
              style={{ width: "100%", height: 500 }}
              source={{ uri: fav.media[0] }}
            />

            <Button
              onPress={() => this.removeItemValue(fav)}
              title="capmare"
              color="#841584"
            />
          </View>
        ))}
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  fav: {
    backgroundColor: "#999",
    flex: 1,
    width: "100%",
    paddingTop: 150
  }
});

export default Favorites;

removeItemValue 方法仅在我删除所有项目时才有效。 但是当我尝试删除特定项目时,即使它进入 if 语句和控制台日志,它也不会删除该项目。

我尝试了很多删除项目的方法,但我不明白为什么调用 'removeItem' 方法只对整个数组有效。

预先感谢您的帮助。

删除后您没有重新加载项目(没有状态变化)。

删除后调用this.showProduct();即可(会重新加载项目,调用setState会强制render/refresh查看)。

您可以使用 filter 代替 forEach/if。

更新:

if (element === JSON.stringify(favi)) {
  await AsyncStorage.removeItem(element);
  console.log("they are the same");
  this.showProduct();
}

这是一个异步调用,所以使用 promise 否则它不会等待,另外 AsyncStorage.removeItem 将作为回调函数给出响应,所以修改如下

async removeItemValue(favi) {
  AsyncStorage.getAllKeys().then(keys =>
     AsyncStorage.multiGet(keys).then(result => {
       result.map(req => {
         req.forEach(element => {
           if (element === JSON.stringify(favi)) {
             //calling the promise method written below
             return this.removeFromAsyncStorage(element)
             .then(result => {
               console.log(result);
             }).catch(err => {
               console.log(err);
             });
           }
         });
       });
     })
   );
 }



removeFromAsyncStorage(key) {
   return new Promise((resolve, reject) => {
     AsyncStorage.removeItem(key, (err, response) => {
      if(response) {
        resolve(response);
      } else {
        reject(err);
      }
    });
   })
 }