我在使用 JSON.parse 時遇到了這個錯誤。下面是函式。我試圖在我必須首先決議它的專案陣列中獲取物件的值,但它顯示了錯誤。
//function for get the data
const viewUser = async () => {
console.log('Loading');
try {
const keys = await AsyncStorage.getAllKeys()
const item = await AsyncStorage.multiGet(keys)
const data=JSON.parse(item)
} catch (error) {
console.log(error, "problem")
}
};
這是我設定值的函式。使用 math.random 為每個用戶獲取唯一的密鑰。
const saveUser = async () => {
var key = Math.floor(Math.random() * 100);
console.log('Saving');
const userObject = {
firstName: firstName,
secondName: secondName,
email: email,
};
await AsyncStorage.setItem(
key,
JSON.stringify(userObject)
);
console.log('saving done!');
setFirstName('');
setSecondName('');
setEmail('');
};
uj5u.com熱心網友回復:
有效的 JSON 字串必須有雙引號。使用反引號將您的密鑰用雙引號括起來
uj5u.com熱心網友回復:
來自的回傳值AsyncStorage.multiGet(keys)不是字串化的 JSON,而是一個元組陣列。要獲取值,您需要執行以下操作:
const viewUser = async () => {
console.log('Loading');
try {
const keys = await AsyncStorage.getAllKeys()
const items = await AsyncStorage.multiGet(keys)
// items is an array of tuples with first value as the key and second as the value
let data = {}
items.forEach(item => {
data[item[0]] = item[1]
})
} catch (error) {
console.log(error, "problem")
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/387456.html
