React Native - 更新 AsyncStorage 项目嵌套键值?
React Native - Update AsyncStorage item nested key value?
我通过 AsyncStorage
存储了一个用户,如下所示:
// data has a few key/value pairs for the user object
AsyncStorage.setItem('user', JSON.stringify(data));
data
中的 key/value 对之一是 question_count
,值为 10
当用户删除问题时,如何将 AsyncStorage
中的 question_count
值减 1,以便值为 9
?
这是我尝试过的:
AsyncStorage.getItem('user').then(data => {
data.question_count--;
});
但这不会改变值。知道如何实现吗?
你应该在递减后再次保存该值。
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();
我通过 AsyncStorage
存储了一个用户,如下所示:
// data has a few key/value pairs for the user object
AsyncStorage.setItem('user', JSON.stringify(data));
data
中的 key/value 对之一是 question_count
,值为 10
当用户删除问题时,如何将 AsyncStorage
中的 question_count
值减 1,以便值为 9
?
这是我尝试过的:
AsyncStorage.getItem('user').then(data => {
data.question_count--;
});
但这不会改变值。知道如何实现吗?
你应该在递减后再次保存该值。
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();