React Native AsyncStorage getItem返回Promise无法解析问题咨询
Ah, I see the issue here! That weird {"_40":0,"_65":0,"_55":null,"_72":null} output is actually a Promise object's internal state, not your stored shopping list data. Here's why this is happening and how to fix it:
Why You're Seeing This
Your ShoppingListService.getItems() is an async function — all async functions return a Promise by default, not the direct result of the operation. When you call JSON.stringify(ShoppingListService.getItems()), you're converting the Promise itself to JSON, not the resolved data inside it.
Solution 1: Use async/await in componentDidMount
Since React allows componentDidMount to be an async function (it won't disrupt component lifecycle behavior), you can await the Promise to get the actual data:
componentDidMount = async () => { try { // Wait for the Promise to resolve and get the data const items = await ShoppingListService.getItems(); alert(JSON.stringify(items)); } catch (error) { // Handle any errors (like AsyncStorage failures) console.error('Error fetching shopping list items:', error); } }
Solution 2: Use Promise .then() Chaining
If you prefer not to use async/await in the lifecycle method, you can handle the Promise with .then():
componentDidMount() { ShoppingListService.getItems() .then(items => { alert(JSON.stringify(items)); }) .catch(error => { console.error('Error fetching shopping list items:', error); }); }
Bonus: Improve Your Service Method
Chances are you stored your shopping list as a JSON string (since AsyncStorage only stores strings). You should parse the result when retrieving it, and handle cases where the key doesn't exist yet (returns null):
const key = 'shoppingListItems'; export default class ShoppingListService { static async getItems() { let result = await AsyncStorage.getItem(key); // Parse JSON string back to array, or return empty array if no data return result ? JSON.parse(result) : []; } // ... }
This way, you'll always get an array back instead of a string or null, making it easier to work with in your components.
内容的提问来源于stack exchange,提问作者Ranga B.

