我有來自異步存盤檔案的這段代碼。但是,這只適用于設定字串值的狀態。我該如何處理一組物件?
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>
);
}
uj5u.com熱心網友回復:
使用檔案提到只能string存盤資料。
見https://react-native-async-storage.github.io/async-storage/docs/usage
要存盤Objector Array,您需要JSON.stringify(myObj)在寫入存盤之前使用序列化它,并JSON.parse(myObj)在從 stronage 讀取后立即反序列化using 。
uj5u.com熱心網友回復:
您可以使用JSON.parse(retrievedItemFromStorage)將其決議為陣列/物件
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/404442.html
標籤:
