我试图将对象附加到AsyncStorage中现有的对象数组,但没有成功。任何帮助都是感激的!
当前代码:
const [storageItems, setStorageItems] = useState([]);
const handleHabitCreation = async () => {
setLoading(true);
const newHabit = {
name: name,
color: updatedColor,
days: daysCount,
times: timesCount,
reminder: selectedDate,
description: description,
};
try {
const jsonValue = await AsyncStorage.getItem('@habit');
setStorageItems(jsonValue);
} catch (error) {
console.error(error);
}
const stringifiedHabit = JSON.stringify(newHabit);
setStorageItems([...storageItems, stringifiedHabit]);
try {
await AsyncStorage.setItem('@habit', JSON.stringify(storageItems));
setTimeout(() => {
setLoading(false);
navigation.pop(3);
}, 2500);
} catch (error) {
console.error(error);
}
};
问题是您没有解析字符串化的json数据。您需要解析它以执行任何修改。将状态下的数据保存为解析过的json,并在将其保存到异步存储之前对其进行格式化。试试下面的代码:
try {
const jsonValue = await AsyncStorage.getItem('@habit');
// saving parsed json
const data = JSON.parse(jsonValue)
setStorageItems(data);
} catch (error) {
console.error(error);
}
// state depends on previous state
setStorageItems((prevState) => [...prevState, newHabit]);
或使更短
try {
const jsonValue = await AsyncStorage.getItem('@habit');
let data = JSON.parse(jsonValue) // parse to modify
// push newHabit as well
data.push(newHabit)
setStorageItems(data);
} catch (error) {
console.error(error);
}
在这两种方法中,都将末尾的对象字符串化
await AsyncStorage.setItem('@habit', JSON.stringify(storageItems));