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

React中如何将useState对象正确插入Firebase Firestore数据库?

解决Firestore插入数据出现嵌套结构的问题

你当前的问题出在addDoc的参数写法上:

你传入的{ price }是ES6对象字面量的简写语法,等价于{ price: price }——这会把你的state对象price再包装一层,最终插入Firestore的就是嵌套结构{ price: { vehicleType: "", price: 0 } }。

要得到预期的扁平结构,直接传入price变量本身即可,不需要额外的对象包裹:

修改前的代码:

const docRef = await addDoc(collection(db, "VehiclePrices"), { price });

修改后的代码:

const docRef = await addDoc(collection(db, "VehiclePrices"), price);

这样插入Firestore的文档结构就会是你期望的{ vehicleType: "", price: 0 }。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 16:13:11