addToCart
的else部分正在实时实时更新。之后,useEffect
以及subscriptionCart
的数据都不会更新。其他所有设置都正确,没有问题。
另外,请在代码方面对我进行任何优化建议。此后,没有任何重新渲染,上下文状态只会被更新。
组件代码:
import React, {useContext, useEffect, useState} from 'react';
import {View, TouchableOpacity, Image} from 'react-native';
import Text from '../../../components/CustomText';
import colors from '../../../styles/colors';
import SubAddRemCont from './SubAddRemCont';
import {BASE_URL} from '../../../constants/ApiConstants';
import SubCartContext from '../../../context/SubCartContext';
const SubItemCard = ({product, navigation}) => {
const [cartCount, setcartCount] = useState(0);
const {subscriptionCart, addToCart, removeProdCount} = useContext(
SubCartContext,
);
useEffect(() => {
cartItemCount();
console.log(
'Step3:context updated in useEffect cartitemcount',
subscriptionCart,
);
}, [addToCart, subscriptionCart]);
console.log('Step4:context updated ', subscriptionCart);
const cartItemCount = () => {
subscriptionCart.forEach((obj) => {
if (obj.itemId === product.itemId) {
console.log('itemid', obj.itemId);
setcartCount(obj.quantity);
}
});
};
if (!product) {
return null;
}
return (
<View
style={{
flexDirection: 'row',
height: 150,
borderRadius: 6,
backgroundColor: colors.bg_white,
elevation: 8,
paddingTop: 23,
paddingBottom: 18,
paddingHorizontal: 16,
marginBottom: 23,
}}>
<Image
source={{uri: BASE_URL + product.image}}
style={{width: 100, height: 100}}
/>
<View style={{justifyContent: 'space-between', flex: 1}}>
<TouchableOpacity>
<Text style={{fontSize: 23, textAlign: 'left'}}>
{product.itemName}
</Text>
<Text
style={{
fontSize: 14,
textAlign: 'left',
}}>
Rs {product.itemPrice}/{product.baseUnit * 1000}gm
</Text>
</TouchableOpacity>
<View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
<SubAddRemCont
onPressAdd={async () => {
console.log('Step1:addtoCart pressed in subItemCard component');
addToCart(product);
}}
onPressRemove={async () => {
removeProdCount(product.itemId);
}}
cartCount={cartCount}
/>
</View>
</View>
</View>
);
};
export default SubItemCard;
上下文代码:
const CartContext = React.createContext();
export const CartProvider = ({children}) => {
const [cartData, setCartData] = useState([]);
const initialiseCart = async () => {
let retrieveCart = await AsyncStorage.getItem('CART_DATA');
if (retrieveCart) {
items = await JSON.parse(retrieveCart);
setCartData(items);
}
};
const updateCart = async (cartList) => {
let data = JSON.stringify(cartList);
await AsyncStorage.setItem('CART_DATA', data);
setCartData(cartList);
console.log('UPDATED_CART', cartList);
};
const addToCart = async (cartItem) => {
const retrieveCart = await AsyncStorage.getItem('CART_DATA');
let item = [];
if (retrieveCart) {
console.log('CART_NOT_EMPTY');
item = await JSON.parse(retrieveCart);
console.log('cartnotEmpty pushed');
const filtered = item.filter((prod) => {
console.log(prod.itemId, cartItem.itemId);
return prod.itemId === cartItem.itemId;
});
if (filtered.length > 0) {
console.log('SAME_ITEM_FOUND_INCRIMENT_QUANTITY');
const pos = item
.map((prod) => {
return prod.itemId;
})
.indexOf(cartItem.itemId);
item[pos].quantity += 1;
} else {
cartItem.quantity = 1;
item.push(cartItem);
}
} else {
cartItem.quantity = 1;
item.push(cartItem);
}
SnackbarCustom('Product added to cart');
updateCart(item);
};
const removeProdCount = async (itemId) => {
const retrieveCart = await AsyncStorage.getItem('CART_DATA');
let item = [];
console.log('CART_NOT_EMPTY');
item = await JSON.parse(retrieveCart);
console.log('cartnotEmpty pushed');
console.log('SAME_ITEM_FOUND_INCRIMENT_QUANTITY');
const pos = item
.map((prod) => {
return prod.itemId;
})
.indexOf(itemId);
item[pos].quantity -= 1;
updateCart(item);
};
const addProdCount = async (itemId) => {
const retrieveCart = await AsyncStorage.getItem('CART_DATA');
let item = [];
console.log('CART_NOT_EMPTY');
item = await JSON.parse(retrieveCart);
console.log('cartnotEmpty pushed');
console.log('SAME_ITEM_FOUND_INCRIMENT_QUANTITY');
const pos = item
.map((prod) => {
return prod.itemId;
})
.indexOf(itemId);
item[pos].quantity += 1;
updateCart(item);
};
const removeProd = async (itemId) => {
const retrieveCart = await AsyncStorage.getItem('CART_DATA');
const item = await JSON.parse(retrieveCart);
const removeItems = item.filter((prod) => prod.itemId !== itemId);
updateCart(removeItems);
};
const clearCart = async () => {
updateCart([]);
await AsyncStorage.removeItem('CART_DATA');
};
return (
<CartContext.Provider
value={{
clearCart,
cartData,
addToCart,
addProdCount,
removeProdCount,
initialiseCart,
removeProd,
}}>
{children}
</CartContext.Provider>
);
};
export default CartContext;