使用 AsyncStorage 在 React Native 中执行 CRUD 操作
Perform CRUD Operation In React Native Using AsyncStorage
*// Creating An Array
const someArray = [1,2,3,4];
return AsyncStorage.setItem('somekey', JSON.stringify(someArray))
.then(json => console.log('success!'))
.catch(error => console.log('error!'));
//Reading An Array
return AsyncStorage.getItem('somekey')
.then(req => JSON.parse(req))
.then(json => console.log(json))
.catch(error => console.log('error!'));
*
如何更新数组的特定索引并删除索引
例如,新数组应该是 {1,A,3}
对于 AsyncStorage,最好将数据结构视为不可变的。所以基本上,要执行更新,你可以抓住你想要的东西,但是弄乱它,然后把它放回同一个键下。
return AsyncStorage.getItem('somekey')
.then(req => JSON.parse(req))
.then(json => {
const temp = json;
temp[2] = 'A';
temp.pop(); // here it's [1, A, 2]
AsyncStorage.setItem('somekey', JSON.stringify(temp));
})
.catch(error => console.log('error!'));
然后要删除任何项目,只需执行 AsyncStorage.removeItem('somekey')
。 AsyncStorage
没有直接操作让你做更深层次的更新,只是一个key/value数据集。
*// Creating An Array
const someArray = [1,2,3,4];
return AsyncStorage.setItem('somekey', JSON.stringify(someArray))
.then(json => console.log('success!'))
.catch(error => console.log('error!'));
//Reading An Array
return AsyncStorage.getItem('somekey')
.then(req => JSON.parse(req))
.then(json => console.log(json))
.catch(error => console.log('error!'));
*
如何更新数组的特定索引并删除索引
例如,新数组应该是 {1,A,3}
对于 AsyncStorage,最好将数据结构视为不可变的。所以基本上,要执行更新,你可以抓住你想要的东西,但是弄乱它,然后把它放回同一个键下。
return AsyncStorage.getItem('somekey')
.then(req => JSON.parse(req))
.then(json => {
const temp = json;
temp[2] = 'A';
temp.pop(); // here it's [1, A, 2]
AsyncStorage.setItem('somekey', JSON.stringify(temp));
})
.catch(error => console.log('error!'));
然后要删除任何项目,只需执行 AsyncStorage.removeItem('somekey')
。 AsyncStorage
没有直接操作让你做更深层次的更新,只是一个key/value数据集。