簡體   English   中英

如何從 Cloud Firestore 獲取數據然后對其進行過濾、映射然后返回?

[英]How to get data from cloud firestore then filter it, map it then return it?

我試圖從 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 中返回它

當您從 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=>{})替換為onSnapshot(snapshot=>{})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM