如何在 react-native 中从 AsyncStorage 中删除特定项目?

How to delete a specific item from AsyncStorage in react-native?

我想删除一个特定的 post,但是当我点击按钮时没有任何反应,我不知道我错过了什么

函数

removePost = async (post_id) => {
try {

    const posts = await AsyncStorage.getItem('posts');
    let postsFav = JSON.parse(postsJSON);
    postsItems = postsFav.filter(function(e){ return e.post_id == post_id })
    AsyncStorage.removeItem('posts', postsItems);

} catch(error) {

}};

按钮

<Button onPress={this.removePost.bind(this, item.post_id)}>

这里你要做的是从数组中删除项目,然后将它保存到本地存储

 removePost = async (post_id) => {
 try {
  const posts = await AsyncStorage.getItem('posts');
  let postsFav = JSON.parse(postsJSON);
  postsItems = postsFav.filter(function(e){ return e.post_id == post_id 
 })

 var index = array.indexOf(postsItems); // we are finding index of array 
 we want to remove form store array in AsyncStorage .  
  if (index > -1) {
   postsFav.splice(index, 1); //
  }
  AsyncStorage.setItem('post',postsFav); // saving remains array in local storage

} catch(error) {

}};

然后将数组保存到AsyncStorage中, 希望这对您有所帮助,如果您有任何疑问,请告诉我 谢谢

您可以使用 AsyncStorage.setItem()posts 更新为 postItems

removePost = async (post_id) => {
try {
  const posts = await AsyncStorage.getItem('posts');
  let postsFav = JSON.parse(posts);
  const postsItems = postsFav.filter(function(e){ return e.post_id !== post_id });

  // updating 'posts' with the updated 'postsItems'
  await AsyncStorage.setItem('posts', JSON.stringify(postsItems));

} catch(error) {
  console.log('error: ', error);
}};  

key_name 从删除和要删除的项目:-

AsyncStorage.removeItem('key_name', 项目);