首页 > 解决方案 > 在反应本机redux中将对象连接到数组中

问题描述

我在使用 redux 将对象连接到数组时遇到问题。当用户单击按钮时,我想将对象连接到数组中,但总是显示一个错误,称为无法读取 null 的属性“concat”。这是我的代码:

  addToCartHandler= ()=>{
    const {phoneNumber,accessToken,ctr} = this.props;
    let {dataSource} = this.state;
    const cart = {title:dataSource.title,image:dataSource.image,id:dataSource.id,count:ctr,price:(dataSource.price-dataSource.discount)*ctr};
    this.props.onCart(cart);}
    .
    .
    .
    .
    
    const mapDispatchToProps = dispatch => {
  return {
    onLogin: () => dispatch({ type: actionTypes.SAVEPHONE }),
    onToken: token => dispatch({ type: actionTypes.SAVEACCESSTOKEN, token }),
    onCart:(cart)=>dispatch({type:actionTypes.CARTPRODUCT,cart})
  }
    
}

这是我的减速机:

const initialState = {
   cartProduct:[],
}

const ShopReducer = (state=initialState,action)=>{
    switch(action.type){
        case actionTypes.CARTPRODUCT:
        return {
            ...state,
            cartProduct:state.cartProduct.concat(action.cart)
        }
        default:
        return state
    }
}

标签: react-nativeredux

解决方案


您不能将数组与对象连接起来。而是用数组包装您的对象,如代码段所示

const initialState = {
   cartProduct:[],
}

const ShopReducer = (state=initialState,action)=>{
    switch(action.type){
        case actionTypes.CARTPRODUCT:
        return {
            ...state,
            cartProduct:state.cartProduct.concat([action.cart]) // change here
        }
        default:
        return state
    }
}

没测试!!希望能帮助到你 :)


推荐阅读