You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native AsyncStorage getItem返回Promise无法解析问题咨询

Fixing AsyncStorage Data Retrieval Issue

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.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:34:20