簡體   English   中英

返回函數不會在 React 中呈現

[英]return function doesn't render in React

我正在嘗試在 React 中實現購物車。 我已經為我的購物車創建了一個上下文來處理購買的數量並且它工作正常。 但是,我在將購物車上下文中的數據顯示到購物車頁面時遇到了問題。 這是我將購買的商品顯示到購物車頁面的代碼。

export class Cart extends React.Component {

    constructor(props) {
        super(props);
    }

    render(){
        return (
            <>
                <div>
                    <h1>Cart</h1>
                </div>
                <CartContext.Consumer>
                    {
                        (cartContext) =>{
                            const {productsToPurchase} = cartContext
                            console.log(productsToPurchase)
                            if (productsToPurchase.length === 0){
                                return(<h1>Cart is empty</h1>)
                            }
                            else {
                                productsToPurchase.map(
                                    (product) =>{
                                        // console.log works fine
                                        console.log("Reached Else Statment")
                                        console.log(product.itemId)
                                        // return doesn't work
                                        return(
                                            <h1 key={product.itemId + "-cart"}> 8525552 </h1>
                                        )
                                })
                            }
                        }
                    }
                </CartContext.Consumer>
            </>
        )
    }

}

我做了同樣的事情,它奏效了。 我不知道為什么我的映射函數沒有顯示我需要的數據。 請查看評論以獲取更多詳細信息

你錯過了回報。 您應該返回 productsToPurchase.map() 的結果

<CartContext.Consumer>
                    {
                        (cartContext) =>{
                            const {productsToPurchase} = cartContext
                            console.log(productsToPurchase)
                            if (productsToPurchase.length === 0){
                                return(<h1>Cart is empty</h1>)
                            }
                            else {
                                return productsToPurchase.map(
                                    (product) =>{
                                        // console.log works fine
                                        console.log("Reached Else Statment")
                                        console.log(product.itemId)
                                        // return doesn't work
                                        return(
                                            <h1 key={product.itemId + "-cart"}> 8525552 </h1>
                                        )
                                })
                            }
                        }
                    }
                </CartContext.Consumer>

暫無
暫無

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

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