首页 > 解决方案 > TypeError: users.map is not a function, 试图获取 firestore 文档

问题描述

我遇到这个错误,上面写着: TypeError: users.map is not a function 我的代码似乎有什么问题?

const [users, setUsers] = useState([]);

  const getData = async () => {
    try {
      const usersRef = firestore.collection("users").doc(id);
      const doc = await usersRef.get();
      if (!doc.exists) {
        console.log("No such document!");
      } else {
        setUsers(doc.data());
      }
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    getData();
  }, []);

如果我愿意console.log(doc.data()),它会显示正确的数据。当我这样做时显示此错误:

 {users &&
        users.map((index) => {
          <li>{index.firstName}</li>;
        })}

更新: doc.data() 是一个对象

标签: javascriptreactjsfirebasegoogle-cloud-firestore

解决方案


usersRef的初始化如下:

const usersRef = firestore.collection("users").doc(id);

由于您doc在最后包含一个调用,因此引用指向users集合中的单个文档。所以你doc是一个单一DocumentSnapshot的并且doc.data()是单个用户文档的JSON,这解释了为什么它没有map方法(如错误消息所述)。


如果要加载所有用户,则需要从以下内容开始:

const usersRef = firestore.collection("users");

如果要加载所有用户的子集,可以向其中添加条件 ( .where(...))。


如果您getData加载所需的数据:单个用户,您可能希望将其作为单个用户的数组传递给您的渲染代码:

setUsers([doc.data()]); // Note the [] in there, those are new

如果您的代码只是每个人都应该获得一个用户,我建议更改您的状态挂钩和引用的名称,并更新渲染代码以反映这一点,因为users该名称意味着有多个元素,并且是只会导致持续的混乱。


推荐阅读