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

调用Appwrite封装的getData方法后,对返回值调用map报undefined错误

问题原因及修复方案

核心错误原因

  • 你定义的getData方法没有正确返回Promise执行结果:async函数内部你仅调用了promise.then但没有将整个Promise链返回,方法默认返回undefined,因此在dashboard中await api.getData()拿到的data值为undefined,调用map方法自然触发报错。
  • 额外注意:你在useEffect末尾打印postItems拿不到最新值,是因为useEffect的闭包特性,只会捕获组件挂载时的初始state值。

代码修复步骤

1. 修复appwrite.js中的getData方法

推荐用更清晰的async/await语法改写,避免嵌套的then调用:

getData: async () => {
  try {
    const response = await appwrite.database.listDocuments('61713e3e5257a');
    console.log(response.documents);
    return response.documents;
  } catch (error) {
    console.log(error);
    throw error; // 抛出错误让上层调用方可以捕获处理
  }
},

如果你要保留原有的then写法,只要加return即可:

getData: async () => {
  let promise = appwrite.database.listDocuments('61713e3e5257a');
  // 这里新增return,把Promise链返回出去
  return promise.then(function (response) {
      console.log(response.documents) //response.documents is a array
      return response.documents
  }, function (error) {
      console.log(error); // Failure
      throw error; // 抛出错误方便上层捕获
  });
},

2. 优化dashboard.js中的状态更新逻辑

不需要循环调用setPostItems,一次批量更新性能更好,也能避免不必要的重渲染:

const [postItems, setPostItems] = useState([])

useEffect(() => {
    const getPostData = async () => {
        try {
                const data = await api.getData()
                // 批量处理数据后一次性更新状态
                const formattedData = data.map((doc) => ({
                    location: doc.location,
                    date: doc.date,
                    text: doc.experience
                }))
                setPostItems(formattedData)
        } catch (error) {
            console.log(error.message);
        }
    }
    getPostData()
}, [])

// 如果要查看更新后的postItems,单独加useEffect监听
useEffect(() => {
  console.log(postItems)
}, [postItems])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:15:03