React Native中如何正确使用AsyncStorage multiGet获取已存储数据?
Hey there! Let's work through this AsyncStorage multiGet issue step by step—you're already halfway there since your multiSet is working perfectly.
First, Let's Clarify the Correct keys Format for multiGet
The biggest gotcha here is mixing up the parameter formats between multiSet and multiGet:
multiSetexpects a 2D array (each entry is a[key, value]pair)multiGetonly needs a 1D array of string keys—no nested arrays, just the exact key names you stored.
For your specific case, since you stored @BarcodeList and @ScannedBarcode, your keys array should be:
const keys = ['@BarcodeList', '@ScannedBarcode'];
Working multiGet Examples
Here are two common implementation styles that should work for your app:
1. Callback Style (Matching the Docs Example)
const keys = ['@BarcodeList', '@ScannedBarcode']; AsyncStorage.multiGet(keys, (err, stores) => { if (err) { console.error('Failed to fetch data:', err); return; } // `stores` is a 2D array where each entry is [key, value] stores.forEach(([key, value]) => { console.log(`Key: ${key}, Raw Value: ${value}`); // Don't forget to parse the JSON for your barcode list! if (key === '@BarcodeList' && value) { const parsedBarcodeList = JSON.parse(value); console.log('Parsed Barcode List:', parsedBarcodeList); } }); });
2. Async/Await Style (Cleaner & More Modern)
This is my preferred approach since it avoids callback nesting:
try { const keys = ['@BarcodeList', '@ScannedBarcode']; const stores = await AsyncStorage.multiGet(keys); stores.forEach(([key, value]) => { console.log(`Key: ${key}, Raw Value: ${value}`); if (key === '@BarcodeList' && value) { const parsedBarcodeList = JSON.parse(value); console.log('Parsed Barcode List:', parsedBarcodeList); } }); } catch (err) { console.error('Failed to fetch data:', err); }
Troubleshooting Steps If It's Still Not Working
If you're still hitting issues, run through these checks:
- Double-check key spelling & case: AsyncStorage keys are case-sensitive. Make sure
@BarcodeListinmultiGetmatches exactly what you used inmultiSet(no typos like@barcodeList). - Verify keys exist in storage: Use
getAllKeys()to confirm your target keys are actually stored:const allStoredKeys = await AsyncStorage.getAllKeys(); console.log('All stored keys:', allStoredKeys); - Handle null/empty values: If a key doesn't exist,
valuewill benull. Add a check before parsing JSON to avoid errors:if (key === '@BarcodeList' && value !== null) { const parsedList = JSON.parse(value); // Use the parsed data } else { console.log(`Key ${key} has no value stored`); } - Check for error details: Always log the
errobject in callbacks or catch blocks—it will tell you exactly what's wrong (e.g., permission issues, invalid key formats).
内容的提问来源于stack exchange,提问作者Nerius Jok
相关产品推荐
相关产品推荐

