我所有的购物车商品都保持在redux状态,每当我加载其他组件时,购物车商品就会被重置。例如,在我的购物车中,我选择了6根香蕉,总价为$ 3。我转到“水果”页面,再添加2个香蕉。当Fruits组件加载时,购物车状态会重置,而不是总共以8美元的价格出售8个香蕉,而我最终只用1美元的价格购买了2个香蕉。我认为这是因为在我的“水果”页面中,当我从Firebase加载产品时设置了状态,并且我认为因为从Firebase中设置了Bananas项目,所以它没有从我的Redux购物车中结转的数量。
let itemsRef = db.ref('/productInfo/0/Fruits');
class Fruits extends Component {
static navigationOptions = {
title: 'Fruits',
};
constructor(props) {
super(props);
this.state = {
items: [],
filtered: []
}
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
itemsRef.on('value', (snapshot) => {
let data = snapshot.val();
let items = Object.values(data);
this.setState({items});
this.setState({
filtered: items
});
});
}
componentWillReceiveProps(nextProps) {
this.setState({
filtered: nextProps.items
});
}
handleChange(e) {
let currentList = []
let newList = []
if (e.toString() !== "") {
currentList = this.state.items
newList = currentList.filter(item => {
const lc = item.name.toString().toLowerCase()
const filter = e.toString().toLowerCase()
return lc.includes(filter)
})
} else {
newList = this.state.items
}
this.setState({
filtered: newList
});
}
render() {
return (
<SafeAreaView style ={{flex:1, marginTop:30}}>
<Searchbar
placeholder="Search"
onChangeText= {(term) => { this.handleChange(term) }}
style = {{marginHorizontal: 20}}
/>
{
this.state.items.length > 0
? <CategoryProductsPage products={this.state.filtered} onPress={this.props.addItemToCart} width = {width}/>
: <Text></Text>
}
</SafeAreaView>
);
}
}
const mapDispatchToProps = (dispatch) => {
return {
addItemToCart: (product) => dispatch({ type: 'ADD_TO_CART', payload: product })
}
}
export default connect(null, mapDispatchToProps)(Fruits);
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}
});
理想情况下,我希望我的redux cart状态在整个应用程序中是通用的,除非用户增加或减少数量,否则不应更改它。我仅在“类别组件”页面上遇到此错误,并且我相信这是因为我在构造函数和componentDidMount中显示Firebase产品和代码的方式。我面临的挑战是如何在不更改状态的情况下合并和导入Firebase产品。
购物车代码:
import {ADD_TO_CART, REMOVE_FROM_CART, SUB_QUANTITY, ADD_QUANTITY} from './actions';
const initialState = {
cart: [
],
totalQuantity: 0,
total: 0.0
};
const updateDeleteProductList = (updateProduct, productList) => {
return productList.map(product => {
if (product.name === updateProduct.name) {
updateProduct.frequency -=1;
updateProduct.totalPrice = (parseFloat(updateProduct.totalPrice) - product.price).toFixed(2)
return updateProduct;
}
return product;
});
};
const updateDeleteAllProductList = (updateProduct, productList) => {
return productList.map(product => {
if (product.name === updateProduct.name) {
updateProduct.frequency = 0;
updateProduct.totalPrice = 0;
return updateProduct;
}
return product;
});
};
const updateAddProductList = (updateProduct, productList) => {
return productList.map(product => {
if (product.name === updateProduct.name) {
updateProduct.frequency +=1;
//state.totalPrice = (parseFloat(state.totalPrice) + count).toFixed(2)
updateProduct.totalPrice = (parseFloat(updateProduct.totalPrice) + product.price).toFixed(2)
return updateProduct;
}
return product;
});
};
const cartItems = (state = initialState, action) => {
switch(action.type) {
case ADD_TO_CART:
console.log("Cart product screen payload" + JSON.stringify(action.payload))
let addedItem = action.payload
//check if the action id exists in the addedItems
let existed_item= state.cart.find(item=> action.payload.name === item.name)
console.log("WHAT IS EXISTED ITEM " + JSON.stringify(existed_item))
if(existed_item)
{
// addedItem.frequency += 1
// addedItem.totalPrice = (parseFloat(addedItem.totalPrice) + action.payload.price).toFixed(2)
let updatedProductList = updateAddProductList(action.payload,state.cart);
return{
...state,
cart: updatedProductList,
total: (parseFloat(state.total) + addedItem.price).toFixed(2)
}
}
else{
addedItem.frequency = 1;
addedItem.totalPrice = (parseFloat(addedItem.totalPrice) + action.payload.price).toFixed(2)
//calculating the total
let newTotal = (parseFloat(state.total) + addedItem.price).toFixed(2)
return{
...state,
cart: [...state.cart, addedItem],
total : newTotal
}
}
case REMOVE_FROM_CART:
let itemToRemove = action.payload
console.log("REMOVE ALL" + JSON.stringify(action.payload))
let new_items = state.cart.filter(item=> action.payload.id !== item.id)
// let deletedProducts = updateDeleteAllProductList(action.payload, state.cart)
itemToRemove.totalPrice = 0
//calculating the total
let newTotal = state.total - (itemToRemove.price * itemToRemove.frequency )
//let newTotal = (parseFloat(state.total) - action.payload.totalPrice).toFixed(2)
return{
...state,
cart: new_items,
total: newTotal
}
case ADD_QUANTITY:
// let addItem = action.payload
// console.log('additem is' + JSON.stringify(addItem))
// addItem.frequency += 1
let updatedProductList = updateAddProductList(action.payload,state.cart);
let newTotalAfterAdd = (parseFloat(state.total) + action.payload.price).toFixed(2)
return{
...state,
cart: updatedProductList,
total: newTotalAfterAdd
}
case SUB_QUANTITY:
let lastItemGone = action.payload
//if the qt == 0 then it should be removed
if(action.payload.frequency === 1){
let new_items = state.cart.filter(item=> action.payload.id !== item.id)
lastItemGone.totalPrice = 0
let newTotal = (parseFloat(state.total) - action.payload.price).toFixed(2)
return{
...state,
cart: new_items,
total: newTotal
}
}
else {
// addedItem.frequency -= 1
let updatedProductList = updateDeleteProductList(action.payload,state.cart);
console.log("updatedProductlist" + JSON.stringify(updatedProductList))
// const newState = state.set( 'orderProducts', updatedProductList).set('lastOperation', action.type);
// return newState;
// let newCart = state.cart
// for (let i =0; i<newCart.length; i++){
// if(addedItem.name === newCart[i].name){
// newCart[i].frequency -=1
// }
// }
// console.log("yo new cart is" + JSON.stringify(newCart))
let newTotal = (parseFloat(state.total) - action.payload.price).toFixed(2)
return{
...state,
cart: updatedProductList,
total: newTotal
}
}
default:
return state;
}
}