单击添加按钮时,数据将被添加到购物车,但是添加后页面不会自动刷新。如果我添加钩子React.useState()并在单击按钮时更新状态,则在分派之后页面将重新呈现。
据我了解,每当状态更新时,页面就会重新呈现。
答案 0 :(得分:0)
发生这种情况是因为您对Redux存储进行了突变。 在您的代码中:
case CartActionTypes.ADD: {
let itemExists = state.cart.find(cart => cart.productId === action.product.productId);
if (itemExists) {
itemExists.count = itemExists.count + 1;
return {
...state,
...state.cart
};
} else {
let cart: ICart = { productId: action.productId, product: action.product, count: 1 };
state.cart.push(cart);
return {
...state,
...state.cart
};
}
}
切换到
case CartActionTypes.ADD: {
let itemExists = state.cart.find(cart => cart.productId === action.product.productId);
if (itemExists) {
itemExists.count = itemExists.count + 1;
return {
...state,
cart: [...state.cart, itemExists]
};
} else {
let cart: ICart = { productId: action.productId, product: action.product, count: 1 };
return {
...state,
cart: [...state.cart, cart]
};
}
}