【问题标题】:How to get data from cloud firestore then filter it, map it then return it?如何从 Cloud Firestore 获取数据然后过滤它,映射它然后返回它?
【发布时间】:2021-02-04 13:26:45
【问题描述】:

我正在尝试从 firestore 获取数据,然后对其进行过滤,然后像这样映射它:

return Inventory
.filter(x =>x["sub_category"] === item && x["category"] === category)
.map(({id, item, price, quantity, image})=>{

//sets the default value for the item with that specific id
const defVal = parseInt((selectedQty.id === id)?selectedQty.qty:0)

return (
    <React.Fragment key={uuid()}>
        <div className="card">
            <img src={image()} alt={item} />
            <p>{item}</p>
            
            <div className="innerBox">
                <div className="dropdown">
                    <label htmlFor="quantity">Qty:</label>
                    <select id="quantity" defaultValue={defVal===0?1:defVal} onChange={e => {
                        e.preventDefault()
                        setSelectedQty({id, qty: parseInt(e.target.value)})
                    }}>
                    {
                        Array(quantity).fill().map((_, i)=> {
                            if(i===0){
                                return <option key={uuid()} value={0}>-</option>
                            }else{
                                return <option key={uuid()} value={i} >{i}</option>
                            }
                        })
                    }
                    </select>
                </div>
                <b>$ {price}</b>
            </div>
            <button type="submit" onClick={()=> {
                addToCart(id, item, parseInt(finalQty), price, image(), parseInt(finalQty)*parseFloat(price))
                setSelectedQty({id:null, qty: 0})
            }}>Add to Cart</button>
        </div>
    </React.Fragment>
)})

目前我正在使用 Inventory Array,但我想切换到 Firestore,但我不知道该怎么做。我知道步骤 db.collection().get().then(etc...) 但我不知道如何映射它以将其返回到 Then

【问题讨论】:

    标签: javascript reactjs google-cloud-firestore return es6-promise


    【解决方案1】:

    当您从 Cloud Firestore 获取数据时,它会返回一个文档/集合快照。

    文档:

    db.collection("colName").doc("docID").get().then(docSnapShot=>{
        const docID = docSnapShot.id;
        const docData = docSnapShot.data();
    })
    

    收藏:

    db.collection("colName").get().then(colSnapShot=>{
        const isEmpty = colSnapShot.empty;
        const docsData = colSnapShot.docs.forEach(docSnapShot=>{
            return docSnapShot.data();
        })
    })
    

    我相信您的解决方案将如下所示:

    let arrOfDocs = await db.collection("colName").get().then(colSnapShot=>{
        return colSnapShot.docs.map(docSnapShot=>{
            return docSnapShot.data();
        })
    })
    

    请注意,要收听实时更新,请将 get().then(snapshot=&gt;{}) 替换为 onSnapshot(snapshot=&gt;{})

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      相关资源
      最近更新 更多