2016-09-14 42 views
1

我已經用戶經由AsyncStorage存儲這樣的:React Native - 更新AsyncStorage項目嵌套鍵值?

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

一個在data鍵/值對是question_count10

當用戶刪除一個問題的值,我怎樣才能遞減question_count值爲1 AsyncStorage所以值是9

這裏是我的嘗試:

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

但是,這並不能改變價值。任何想法如何做到這一點?

回答

8

您應該在減量後再次保存該值。

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(); 
+0

正是我所需要的。謝謝! – Wonka