javascript - 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() 是一个对象
解决方案
您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
该名称意味着有多个元素,并且是只会导致持续的混乱。
推荐阅读
- laravel - 在sql查询Laravel中连接两列
- swiftui - 将数据数组传递到另一个数据数组
- google-cloud-platform - 访问权限对于更改模板访问容器注册表无效
- github - 为什么谷歌分析不能在 github 页面上托管的网站上运行?
- javascript - 每次页面加载时都会显示导航栏组件
- postgresql - Postgres db 到雪花的迁移
- android-studio - "import proguard.annotation.Keep" => "无法解析符号'annotation'"
- spring-boot - Spring 的 HATEOAS CollectionModelAssembler 不解析属性注入的 RequestMapping 值
- php - 如何在 sql 数据库中清理和存储小数点
- spring - Spring JPA 本机查询从 postgres 的查询中删除了一些列