0

好的,这是我在ProductScreen中添加删除购物车的按钮:

    <TouchableOpacity onPress={()=>{this.addToCart()}}>
                   <Text>add to cart</Text>
    </TouchableOpacity>

   <TouchableOpacity onPress={()=>{this.props.updateCart({'numberOfProducts':0,'products':[]})}}>
                   <Text>Erase cart</Text>
    <TouchableOpacity>

addToCart函数:

addToCart = () =>{
    let currentCartProducts = this.props.cart;
    currentCartProducts.numberOfProducts++;
    this.setState({
        currentProductToAdd:Object.assign(
            this.state.currentProductToAdd,
                {
                    'toalPriceOfProductWithExtras': this.props.navigation.getParam('price') * this.state.value,
                    'piecesOfProduct': this.state.value,
                }
        )
    })
    currentCartProducts.products.push(this.state.currentProductToAdd);
    this.props.updateCart(currentCartProducts);
}

购物车减速器

const INITIAL_STATE = {'numberOfProducts':0,'products':[]};

export default (state = INITIAL_STATE, action) => {
  switch(action.type) {
    case 'update':
      return action.payload;
    default: 
     return state;
  }
};

The Cart动作

export const updateCart = (val) => {
    return{
      type: 'update',
      payload: val
    };
  };

还有CartScreen 组件WillReceiveProps,我想在其中呈现购物车中的产品。redux 工作得很好,我已经正确存储了所有数据,但它们没有渲染!

componentWillReceiveProps(nextProps) {
    console.log('I m in componentWillReceiveProps')
    if (this.props.cart !== nextProps.cart) {
        console.log('OLD CART')
        console.log(this.props.cart)
        console.log('NEW CART')
        console.log(nextProps.cart)
    }
}

当我按添加时它不起作用,但是当我按删除时它起作用!

一加一删:

I m in componentWillReceiveProps
OLD CART
Object {
  "numberOfProducts": 1,
  "products": Array [
    Object {
      "extras": undefined,
      "piecesOfProduct": 1,
      "productName": "Chips",
      "productPrice": 0,
      "restaurantAddres": "Tay House 300 Bath St",
      "restaurantName": "time2dine - Spaces",
      "toalPriceOfProductWithExtras": 0,
    },
  ],
}
NEW CART
Object {
  "numberOfProducts": 0,
  "products": Array [],
}

再按一次删除后:

I m in componentWillReceiveProps
OLD CART
Object {
  "numberOfProducts": 0,
  "products": Array [],
}
NEW CART
Object {
  "numberOfProducts": 0,
  "products": Array [],
}

这很奇怪,因为在第二次按下删除购物车道具时是相同的......但是当我添加并且道具更改时没有显示任何内容。

谢谢 !

4

1 回答 1

0

我认为您没有正确更新商店。

case 'update':`
 return {...state, ...action.payload};

cartReducer.js. 您应该记住使用扩展运算符,否则在您更新商店时状态将是相同的,这将导致componentWillReceiveProps无法按预期工作。希望它有帮助!!..快乐编码!

于 2020-03-26T14:12:27.990 回答