【问题标题】:Why my type number value gets stored as a string in Firestore?为什么我的类型编号值在 Firestore 中存储为字符串?
【发布时间】:2021-11-27 22:36:46
【问题描述】:

老实说,我不知道为什么不工作,它甚至没有意义,而且它在你能发现一些我看不到的东西之前就开始工作了。

我正在使用类型号将一些数据更新到 Firebase,但即使我使用的是输入类型号,它也被存储为字符串,但由于某种原因它似乎无法正常工作,代码如下:

//Firebase set
const [precio, setPrecio] = useState();
const register = (e) => {
       e.preventDefault();
       const docRef = db.collection('productos_AIB').doc(docId);

       docRef.get().then((doc) => {

           if (doc.exists) 
           {
               window.alert("Ya existe ese producto")
           }
           else {
               
               docRef.set({
                   descripcion: descripcion,
                   tipo: tipo,
                   grado: grado,
                   precio: parseFloat(precio).toFixed(2),
                   cantidad: cantidad,
                   necesita: necesita,
                   id: docRef.id
           }).then((r) => {
               window.alert("Producto agregado")
           })}
   })
}

//Input
<input 
onChange = {(e) => {setPrecio(e.target.valueAsNumber);}}
type = 'number'
pattern = "[0-9]*"
requiredplaceholder="Precio"
/>

如果您需要其他内容,请告诉我,IDK 为什么它停止工作,也许我在没有注意到的情况下更改了某些内容,但我无法发现错误。

更新忘记添加它在 Firestore 中的外观图片:

【问题讨论】:

    标签: reactjs firebase google-cloud-platform google-cloud-firestore


    【解决方案1】:

    可能,“precio”的值来自用户输入,这很可能是文字字符串,而不是数字。所以toFixed() 不会提供你所期望的。要解决这个问题,您应该更改以下代码行:

    precio: parseFloat(precio).toFixed(2),
    

    进入:

    precio: parseFloat(parseFloat(precio).toFixed(2)),
    

    通过这种方式,您可以在 Firestore 中写入一个数字而不是而不是字符串。

    【讨论】:

    • 好吧,这部分工作做了一个小测试,注册了一个价格为 5 的对象,它存储为一个数字,是的,但它没有添加 2 个小数。有什么建议 ?它只是存储为 5 而不是 5.00
    • 另一个问题:为什么它存储为字符串?我的输入是“valueAsNumber”,类型也是“number”。
    • 因为输入总是一个字符串,不管你设置什么类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    相关资源
    最近更新 更多