AsyncStorage 以错误的格式保存数组
AsyncStorage saving array in wrong format
我一直在构建一个日记应用程序,我想在 AsyncStorage 中保存时间,这很有效,但如果我想添加一天,它会变得很奇怪,这是我的功能:
这是 return:
[[[{"date":"t","value":"t","name":"t"}],{"date":"p","value":"p","name":"p"}],{"date":"h","value":"h","name":"h"}]
async function createDay(date: string, journal: string, name: string) {
try {
try {
const getalldays = await AsyncStorage.getItem('@journal')
const alldays = await JSON.parse(getalldays!)
if (JSON.parse(alldays!) !== null) {
console.log('SHORT')
await alldays!.push(JSON.parse(alldays!))
}
const newDay = { date: date, value: journal, name: name }
await alldays.push(newDay)
await AsyncStorage.setItem('@journal', JSON.stringify(alldays))
const newall = await AsyncStorage.getItem('@journal')
console.log(newall)
return;
} catch (error) {
console.log(error)
return;
}
} catch (err) {
console.error(err)
}
}
据我理解的问题,你想以这种格式存储数据
[
{ date: 'h', value: 'h', name: 'h' },
{ date: 'h', value: 'h', name: 'h' },
{ date: 'h', value: 'h', name: 'h' },
{ date: 'h', value: 'h', name: 'h' },
]
我建议您为所有 Storage operations
创建一个帮助文件
第 1 步:
在您的 App.js
所在的位置创建一个名为 storage
的文件夹。现在在 storage
文件夹中,创建一个名为 AsyncStore.js
的文件,它应该如下所示
AsyncStore.js
import AsyncStorage from '@react-native-async-storage/async-storage';
const setData = async (token, value) => {
try {
await AsyncStorage.setItem(token, JSON.stringify(value));
return true;
} catch (e) {
return false;
}
};
const getData = async (token) => {
try {
const jsonValue = await AsyncStorage.getItem(token);
return jsonValue != null ? JSON.parse(jsonValue) : null;
} catch (e) {
return null;
}
};
const removeData = async (token) => {
try {
await AsyncStorage.removeItem(token);
} catch (e) {
return null;
}
};
export default { setData, getData, removeData };
第 2 步:
把你的存储功能createDay
改成这个
async function createDay(date, journal, name) {
try {
const response = await Storage.getData('@journal'); // Get last data stored
let tempData = []; // Make a new array
if (response) tempData = [...response]; // Copy elements if array is not null
tempData.push({ date: 'h', value: 'h', name: 'h' }); // Push New element to array
await Storage.setData('@journal', tempData); // Set new Array in local Storage
} catch (err) {
console.error(err); // Some error while storing data
}
}
结果
我制作了一个示例 Snack here 供您查看工作实施。如果你想检查数据是否被完美存储,你可以检查如下所示
import * as React from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import AsyncStore from './storage/AsyncStore';
export default function App() {
const [JournalData, SetJournalData] = React.useState([]);
React.useEffect(() => {
RestoreData(); // Restoring the last data stored here
}, []);
const RestoreData = async () => {
try {
const response = await AsyncStore.getData('@journal');
if (response) {
console.log(response);
SetJournalData(response);
}
} catch (e) {
console.log(e);
}
};
async function createDay(date, journal, name) {
try {
const response = await AsyncStore.getData('@journal'); // Get last data stored
let tempData = []; // Make a new array
if (response) tempData = [...response]; // Copy elements if array is not null
tempData.push({ date: 'h', value: 'h', name: 'h' }); // Push New element to array
SetJournalData(tempData);
await AsyncStore.setData('@journal', tempData); // Set new Array in local Storage
} catch (err) {
console.error(err); // Some error while storing data
}
}
return (
<View style={styles.container}>
<Button title="Add Some Data" onPress={createDay} />
<Text>{`Listing total ${JournalData.length} items`}</Text>
{JournalData.map((item, index) => (
<Text
key={
index
}>{`item Number = ${index} date = ${item.date} value = ${item.value} name = ${item.name}`}</Text>
))}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
});
我一直在构建一个日记应用程序,我想在 AsyncStorage 中保存时间,这很有效,但如果我想添加一天,它会变得很奇怪,这是我的功能:
这是 return:
[[[{"date":"t","value":"t","name":"t"}],{"date":"p","value":"p","name":"p"}],{"date":"h","value":"h","name":"h"}]
async function createDay(date: string, journal: string, name: string) {
try {
try {
const getalldays = await AsyncStorage.getItem('@journal')
const alldays = await JSON.parse(getalldays!)
if (JSON.parse(alldays!) !== null) {
console.log('SHORT')
await alldays!.push(JSON.parse(alldays!))
}
const newDay = { date: date, value: journal, name: name }
await alldays.push(newDay)
await AsyncStorage.setItem('@journal', JSON.stringify(alldays))
const newall = await AsyncStorage.getItem('@journal')
console.log(newall)
return;
} catch (error) {
console.log(error)
return;
}
} catch (err) {
console.error(err)
}
}
据我理解的问题,你想以这种格式存储数据
[
{ date: 'h', value: 'h', name: 'h' },
{ date: 'h', value: 'h', name: 'h' },
{ date: 'h', value: 'h', name: 'h' },
{ date: 'h', value: 'h', name: 'h' },
]
我建议您为所有 Storage operations
第 1 步:
在您的 App.js
所在的位置创建一个名为 storage
的文件夹。现在在 storage
文件夹中,创建一个名为 AsyncStore.js
的文件,它应该如下所示
AsyncStore.js
import AsyncStorage from '@react-native-async-storage/async-storage';
const setData = async (token, value) => {
try {
await AsyncStorage.setItem(token, JSON.stringify(value));
return true;
} catch (e) {
return false;
}
};
const getData = async (token) => {
try {
const jsonValue = await AsyncStorage.getItem(token);
return jsonValue != null ? JSON.parse(jsonValue) : null;
} catch (e) {
return null;
}
};
const removeData = async (token) => {
try {
await AsyncStorage.removeItem(token);
} catch (e) {
return null;
}
};
export default { setData, getData, removeData };
第 2 步:
把你的存储功能createDay
改成这个
async function createDay(date, journal, name) {
try {
const response = await Storage.getData('@journal'); // Get last data stored
let tempData = []; // Make a new array
if (response) tempData = [...response]; // Copy elements if array is not null
tempData.push({ date: 'h', value: 'h', name: 'h' }); // Push New element to array
await Storage.setData('@journal', tempData); // Set new Array in local Storage
} catch (err) {
console.error(err); // Some error while storing data
}
}
结果
我制作了一个示例 Snack here 供您查看工作实施。如果你想检查数据是否被完美存储,你可以检查如下所示
import * as React from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import AsyncStore from './storage/AsyncStore';
export default function App() {
const [JournalData, SetJournalData] = React.useState([]);
React.useEffect(() => {
RestoreData(); // Restoring the last data stored here
}, []);
const RestoreData = async () => {
try {
const response = await AsyncStore.getData('@journal');
if (response) {
console.log(response);
SetJournalData(response);
}
} catch (e) {
console.log(e);
}
};
async function createDay(date, journal, name) {
try {
const response = await AsyncStore.getData('@journal'); // Get last data stored
let tempData = []; // Make a new array
if (response) tempData = [...response]; // Copy elements if array is not null
tempData.push({ date: 'h', value: 'h', name: 'h' }); // Push New element to array
SetJournalData(tempData);
await AsyncStore.setData('@journal', tempData); // Set new Array in local Storage
} catch (err) {
console.error(err); // Some error while storing data
}
}
return (
<View style={styles.container}>
<Button title="Add Some Data" onPress={createDay} />
<Text>{`Listing total ${JournalData.length} items`}</Text>
{JournalData.map((item, index) => (
<Text
key={
index
}>{`item Number = ${index} date = ${item.date} value = ${item.value} name = ${item.name}`}</Text>
))}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
});