好的,这是我在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 [],
}
这很奇怪,因为在第二次按下删除购物车道具时是相同的......但是当我添加并且道具更改时没有显示任何内容。
谢谢 !