使用Redux在React类组件中添加购物车商品时持续返回undefined如何解决
问题排查方向&修复方案
核心错误点
- reducer中payload取值错误:你在
addToCartaction中直接把商品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
相关产品推荐
相关产品推荐

