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

使用Redux在React类组件中添加购物车商品时持续返回undefined如何解决

问题排查方向&修复方案

核心错误点

  • reducer中payload取值错误:你在addToCart action中直接把商品item作为payload传入,但是reducer里写了var {item} =action.payload,相当于从item对象里找名为item的属性,这个属性不存在,所以拿到的item是undefined。
  • reducer逻辑分支无返回值:初始状态下cartItems是空数组,你写的for循环判断条件i < state.cartItems.length初始为false,循环完全不执行,ADD_TO_CART分支没有返回值,reducer默认返回undefined,导致整个cart模块的state被覆盖为undefined。
  • 组件内取值错误:你在renderRow中打印this.state.cartItems,但cartItems是通过mapStateToProps挂载到组件props上的,组件自身state中没有这个属性,所以打印结果为undefined。

修复代码

修复后的cart reducer

import { ADD_TO_CART } from '../constants'

const initialState = {
    cartItems: [],
    totalPrice :0
}

export const cart = (state = initialState, action) => {
    switch (action.type) {
        case ADD_TO_CART:
            console.log("reducer",action)
            // 直接取payload即可,不需要解构
            const item = action.payload;
            // 若需要判断商品已存在则累加数量,可以在此处加判断逻辑
            const isExisted = state.cartItems.find(cartItem => cartItem.id === item.id);
            if (isExisted) {
                // 已有同款商品的逻辑,比如累加数量,这里按你需求调整
                return {
                    ...state,
                    cartItems: state.cartItems.map(cartItem => 
                        cartItem.id === item.id ? {...cartItem, count: cartItem.count + 1} : cartItem
                    ),
                    totalPrice: state.totalPrice + (item.price || 0)
                }
            }
            // 无同款商品直接追加
            return {
                ...state,
                cartItems: [...state.cartItems, {...item, count: 1}],
                totalPrice: state.totalPrice + (item.price || 0)
            }
        default:
            return state
    }
}

修复后的renderRow方法

renderRow =({item}) =>{
    // 从props取值,而不是state
    console.log(this.props.cartItems)
    return(
      <TouchableHighlight >
      <View style ={styles.card}>
      <Image source={{uri:item.image}} style={styles.image} />
        
        <Icon name="add" size ={20} style= {styles.addToCartBtn} onPress ={() => this.props.addToCartHandler(item)} />
      
       </TouchableHighlight>
    )
  }

内容的提问来源于stack exchange,提问作者Luke Tan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 19:45:03