如何从react-native中删除AsyncStorage中的项目

ach*_*chu 6 react-native

如何从AsyncStorage中删除项目?现在我正在尝试这段代码

AsyncStorage.removeItem('userId');
Run Code Online (Sandbox Code Playgroud)

但这不适合我.

Him*_*edi 29

试试这个:

  async removeItemValue(key) {
    try {
      await AsyncStorage.removeItem(key);
      return true;
    }
    catch(exception) {
      return false;
    }
  }
Run Code Online (Sandbox Code Playgroud)


404*_*ton 6

这就是我所做的,也遇到了类似的问题。当您想根据项目的 id 删除项目时,它非常有效。确保每个项目都有唯一的 ID。

remove_user = async(userid) => {
    try{
        let usersJSON= await AsyncStorage.getItem('users');
        let usersArray = JSON.parse(usersJSON);
        alteredUsers = usersArray.filter(function(e){
            return e.id !== userid.id

        })
        AsyncStorage.setItem('users', JSON.stringify(alteredUsers));
        this.setState({
           users:alteredUsers
        })
    }
    catch(error){
        console.log(error)
    }
};
Run Code Online (Sandbox Code Playgroud)