首页 > 解决方案 > React Native AsyncStorage 不覆盖数据

问题描述

我正在尝试制作一个应用程序,并且我在使用 AsyncStorage 的数组中有一些对象。我需要更改对象的一个​​元素,但如果我尝试更改它,它不会保留这些更改。

我的代码:

save = async () => {
this.state.dataSource.notes = this.state.text;
try {
  AsyncStorage.clear();
  await AsyncStorage.setItem('medicines', JSON.stringify(this.state.dataSource));
} catch (error) {
  console.log('error');
}
this.setModalVisible(!this.state.modalVisible);

存储文本输入的this.state.text值。

this.state.dataSource存储对象数组。

这两个都像他们应该的那样工作。

数组如下所示:

Array = [
item = {
    id: 'id',
    name: 'name',
    brand: 'brand',
    inname: 'inname',
    chosenWeekDay: 'week day',
    androidDate: 'date for android',
    chosenAndroidTime: 'time for android',
    notes: 'notes in a string',
  }]

标签: arraysreact-nativeobjectmobileasyncstorage

解决方案


您需要针对dataSource数组中的特定对象

let { dataSource, text } = this.state;
const yourSpecfiicIndex = 12; // whatever
dataSource[yourSpecfiicIndex].notes = text;

//...

await AsyncStorage.setItem('medicines', JSON.stringify(dataSource));

推荐阅读