【问题标题】:React Native - Update AsyncStorage item nested key value?React Native - 更新 AsyncStorage 项嵌套键值?
【发布时间】:2016-09-14 04:58:03
【问题描述】:

我有一个通过AsyncStorage 存储的用户,如下所示:

// data has a few key/value pairs for the user object
AsyncStorage.setItem('user', JSON.stringify(data));

data 中的一个键/值对是question_count,其值为10

当用户删除一个问题时,我如何将AsyncStorage 中的question_count 值减1,使该值为9

这是我尝试过的:

AsyncStorage.getItem('user').then(data => {
    data.question_count--;
});

但这不会改变价值。知道如何做到这一点吗?

【问题讨论】:

    标签: react-native asyncstorage


    【解决方案1】:

    你应该在减少它之后再次保存这个值。

    AsyncStorage.getItem( 'user' )
        .then( data => {
    
          // the string value read from AsyncStorage has been assigned to data
          console.log( data );
    
          // transform it back to an object
          data = JSON.parse( data );
          console.log( data );
    
          // Decrement
          data.question_count--;
          console.log( data );
    
          //save the value to AsyncStorage again
          AsyncStorage.setItem( 'user', JSON.stringify( data ) );
    
        }).done();
    

    【讨论】:

    • 正是我需要的。谢谢!
    • 如果数据量很大怎么办,到时候我觉得可能需要更多时间
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多