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

React中return函数不渲染,购物车Context数据无法在页面正常显示

问题原因

你在else分支中调用productsToPurchase.map()生成了元素数组,但是没有将map的执行结果返回给Context Consumer的渲染函数,React拿到undefined后不会渲染任何内容,这就是控制台能正常打印、但页面看不到元素的核心原因。

修正方案

只需要在productsToPurchase.map()前添加return关键字即可,修正后的完整代码如下:

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 {
                                // 新增return返回map生成的元素数组
                                return productsToPurchase.map(
                                    (product) =>{
                                        console.log("Reached Else Statment")
                                        console.log(product.itemId)
                                        return(
                                            <h1 key={product.itemId + "-cart"}> 8525552 </h1>
                                        )
                                })
                            }
                        }
                    }
                </CartContext.Consumer>
            </>
        )
    }
}

如果需要给返回的商品列表加公共外层容器,也可以用<>或者<div>把map的结果包裹后再返回。

内容的提问来源于stack exchange,提问作者asem shaat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:54:08