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

时间:2018-05-09 05:25:24

标签: javascript reactjs react-native

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

功能

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)}>

3 个答案:

答案 0 :(得分:0)

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

&#13;
&#13;
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);
}};  
&#13;
&#13;
&#13;

答案 1 :(得分:0)

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

AsyncStorage.removeItem(&#39; key_name&#39;,Items);

答案 2 :(得分:-1)

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

 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中, 希望这会对你有所帮助,如果你有疑问,请告诉我 感谢