- Я уже рассмотрел синтаксис всех компонентов, и они мне кажутся нормальными.
< /li>
Проверяет через консоль, чтобы проверить, правильно ли вызывается диспетчеризация.
< li>Редуктор правильно возвращает новое состояние. - Элементы отображаются в браузере
Однако я по-прежнему не могу совершить покупки корзину я выполнил действие по отображению содержимого, предметов и их суммы; точно так же, как я создал его в компоненте CartPage.jsx, и когда я добавляю продукты, он показывает мне только, что в значке корзины есть элемент.
import { useContext } from "react"
import { CartContext } from "../context/CartContext"
export const CartPage = () => {
const { shoppingList, increaseItem, decreaseItem, removePurchase } = useContext(CartContext)
console.log("Shopping list in CartPage:", shoppingList);
const calculateTotal = () => {
return shoppingList.reduce((total, item) => total + item.price * item.quantity, 0).toFixed(2)
}
const handlePrint = () => {
// print()
};
return (
Name
Price
Quantity
Remove
{
shoppingList.map(item => (
{item.title}
{item.price}
{item.quantity}
decreaseItem(item.id) }>-
{item.quantity}
increaseItem(item.id) }>+
removePurchase(item.id)}>
Remove
))
};
TOTAL:
${calculateTotal()}
1}
> Buy
)
}
import './App.css';
import { Route, Routes, Navigate } from 'react-router-dom';
import { NavBar } from './Components/NavBar';
import { ShoppingPage } from './Pages/ShoppingPage';
import { CartPage } from './Pages/CartPage';
import { ProductsProvider } from './context/ProductsProvider';
import { CartProvider } from './context/CartProvider';
function AppCart() {
return (
);
}
export default AppCart;
- При отладке в консоли с помощью («Добавить покупку:», action.pyload, state); отражает объект в консоли, запрошенные характеристики и количество — это число, которое увеличивается по мере добавления продуктов.
- Тест выполнен с помощью консоли. log «Добавление продукта:» в список покупок отображает данные правильно
- Состояние списка покупок отражает изменения в консоли, а количество обновляется изменения
import { useReducer } from "react";
const initialState = []
export const CartProvider = ({ children }) => {
const shoppingReducer = (state = initialState, action = {}) => {
console.log("Reducer action:", action);
switch (action.type) {
case '[CART Add Purchase]':
console.log("Add Purchase Reducer State:", state);
console.log("Add Purchase:", action.payload, state);
const existingProduct = state.find(item => item.id === action.payload.id);
if (existingProduct) {
return state.map(item =>
item.id === action.payload.id
? {...item, quantity: item.quantity + 1}
: item
);
} else {
return [...state, {...action.payload, quantity: 1 }];
}
case '[CART] Increase item Purchase': // TODO: Add quantity and to modify
console.log("Increase Reducer State:", state);
return state.map(item =>
item.id === action.payload
? {...item, quantity: item.quantity + 1}
: item
);
case '[CART] Decrease item Purchase': // TODO: Add quantity and to modify
return state.map(item =>
item.id === action.payload
? {...item, quantity: item.quantity - 1 }
: item
);
case '[CART] Remove Purchase':
return state.filter(item => item.id !== action.payload)
default:
return state;
}
};
const [shoppingList, dispatch] = useReducer(shoppingReducer, initialState)
console.log("Shopping list in CartPage:", shoppingList);
const addPurchase = (product) => {
console.log("Adding product:", product);
const action = {
type: '[CART Add Purchase]',
payload: product
}
dispatch(action)
}
const increaseItem = (id) => {
const action = {
type: '[CART] Increase item Purchase',
payload: id
}
dispatch(action)
console.log("Increasing item with ID:", id); // Depuration
dispatch({ type: '[CART] Increase item Purchase', payload: id });
};
const decreaseItem = (id) => {
const action = {
type: '[CART] Decrease item Purchase',
payload: id
}
dispatch(action)
};
const removePurchase = (id) => {
const action = {
type: '[CART] Remove Purchase',
payload: id
}
dispatch(action)
};
return (
{children}
)
}
Часть консольной печати:
Adding product: {purchase: {…}}purchase: category: "men's clothing"description: "Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday"id: 1image: "https://fakestoreapi.com/img/81fPKd-2AY ... .jpg"price: 109.95rating: {rate: 3.9, count: 120}title: "Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops"[[Prototype]]: Object[[Prototype]]: Object
CartProvider.jsx:9 Reducer action: {type: '[CART Add Purchase]', payload: {…}}
CartProvider.jsx:12 Add Purchase Reducer State: [{…}]
CartProvider.jsx:13 Add Purchase: {purchase: {…}} [{…}]0: purchase: {id: 1, title: 'Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops', price: 109.95, description: 'Your perfect pack for everyday use and walks in th…to 15 inches) in the padded sleeve, your everyday', category: "men's clothing", …}quantity: 5[[Prototype]]: Objectlength: 1[[Prototype]]: Array(0)
CartProvider.jsx:50 Shopping list in CartPage: [{…}]
CartProvider.jsx:9 Reducer action: {type: '[CART Add Purchase]', payload: {…}}
CartProvider.jsx:12 Add Purchase Reducer State: [{…}]
CartProvider.jsx:13 Add Purchase: {purchase: {…}} [{…}]
CartProvider.jsx:50 Shopping list in CartPage: [{…}]0: purchase: {id: 1, title: 'Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops', price: 109.95, description: 'Your perfect pack for everyday use and walks in th…to 15 inches) in the padded sleeve, your everyday', category: "men's clothing", …}quantity: 6[[Prototype]]: Objectlength: 1[[Prototype]]: Array(0)
- Я уже проверил карту. в ShoppingList (компонент CartPage), и я проверил, отправив напрямую { ...product} в компоненте CartProvider, но все равно ничего
import React, { useContext } from "react";
import { Card } from "../Components/Card";
import { ProductsContext } from "../context/ProductsContext";
import { CartContext } from "../context/CartContext";
export const ShoppingPage = () => {
const { products } = useContext(ProductsContext);
const handleAdd = ( purchase ) =>{
addPurchase({
purchase
});
};
const handleRemove = (id) =>{
removePurchase(id)
};
const {
addPurchase,
removePurchase,
} = useContext(CartContext);
return (
Shopping:
{products.map(product => (
handleAdd(product)}
handleRemove={() => handleRemove(product.id)}
>
))};
);
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... -de-produc