如何使用 useAsyncStorage 设置数组的状态
How to use useAsyncStorage to set the state of an array
我有来自 async storage docs 的代码。但是,这仅适用于设置字符串值的状态。我该如何处理对象数组?
export default function App() {
const [value, setValue] = useState('value');
const { getItem, setItem } = useAsyncStorage('@storage_key');
const readItemFromStorage = async () => {
const item = await getItem();
setValue(item);
};
const writeItemToStorage = async newValue => {
await setItem(newValue);
setValue(newValue);
};
useEffect(() => {
readItemFromStorage();
}, []);
return (
<View style={{ margin: 40 }}>
<Text>Current value: {value}</Text>
<TouchableOpacity
onPress={() =>
writeItemToStorage(
Math.random()
.toString(36)
.substr(2, 5)
)
}
>
<Text>Update value</Text>
</TouchableOpacity>
</View>
);
}
使用文档提到只能存储 string
数据。
见https://react-native-async-storage.github.io/async-storage/docs/usage
要存储 Object
或 Array
,您需要在写入存储之前使用 JSON.stringify(myObj)
对其进行序列化,并在读取后立即使用 JSON.parse(myObj)
进行反序列化来自 stroage.
您可以使用 JSON.parse(retrievedItemFromStorage)
将其解析为 Array/Object
我有来自 async storage docs 的代码。但是,这仅适用于设置字符串值的状态。我该如何处理对象数组?
export default function App() {
const [value, setValue] = useState('value');
const { getItem, setItem } = useAsyncStorage('@storage_key');
const readItemFromStorage = async () => {
const item = await getItem();
setValue(item);
};
const writeItemToStorage = async newValue => {
await setItem(newValue);
setValue(newValue);
};
useEffect(() => {
readItemFromStorage();
}, []);
return (
<View style={{ margin: 40 }}>
<Text>Current value: {value}</Text>
<TouchableOpacity
onPress={() =>
writeItemToStorage(
Math.random()
.toString(36)
.substr(2, 5)
)
}
>
<Text>Update value</Text>
</TouchableOpacity>
</View>
);
}
使用文档提到只能存储 string
数据。
见https://react-native-async-storage.github.io/async-storage/docs/usage
要存储 Object
或 Array
,您需要在写入存储之前使用 JSON.stringify(myObj)
对其进行序列化,并在读取后立即使用 JSON.parse(myObj)
进行反序列化来自 stroage.
您可以使用 JSON.parse(retrievedItemFromStorage)
将其解析为 Array/Object