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

如何在AWS Amplify中等待查询结束并显示加载状态

实现加载状态与活动指示器

要实现查询时显示活动指示器、完成后展示产品的效果,只需添加加载状态管理并配合渲染逻辑即可,具体步骤如下:

1. 添加加载状态变量

用useState声明一个布尔状态来跟踪加载状态,初始值设为false:

const [isLoading, setIsLoading] = useState(false);

2. 修改查询函数

在查询开始前将加载状态设为true,查询完成(无论成功或失败)后重置为false,确保指示器能正常关闭:

const getProduct = async () => {
  try {
    setIsLoading(true); // 启动加载,显示指示器
    if (userId) {
      // 直接用await接收查询结果,替代.then()让代码更简洁
      const products = await DataStore.query(Product, c => c.userID("eq", userId));
      setProducts(products);
    }
  } catch (e) {
    console.error("产品查询失败:", e); // 可选:捕获并打印错误信息
  } finally {
    setIsLoading(false); // 无论结果如何,结束加载状态
  }
};

3. 根据状态渲染对应内容

在组件渲染部分,通过isLoading判断:加载中显示活动指示器,加载完成后展示产品列表:

// 以React Native为例,Web项目可替换为对应加载组件
return (
  <View>
    {isLoading ? (
      <ActivityIndicator size="large" color="#0066cc" />
    ) : (
      <FlatList
        data={products}
        renderItem={({ item }) => <ProductCard product={item} />} // 替换为你的产品展示组件
        keyExtractor={item => item.id}
      />
    )}
  </View>
);

内容的提问来源于stack exchange,提问作者hewa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 17:10:33