React Native AsyncStorage 不会覆盖数据

React Native AsyncStorage not overwriting data

我正在尝试制作一个应用程序,我在使用 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',
  }]

您需要将 dataSource 数组中的特定对象作为目标

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

//...

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

我找到了解决方案:

save = async () => {
  this.changeNotes(this.state.id, 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);
}


 changeNotes( value, note ) {
  for (var i in this.state.dataSource) {
    if (this.state.dataSource[i].id == value) {
      this.state.dataSource[i].notes = note;
      break;
     }
   }
 }