问题描述
我有一个使用useState
的迷你购物车应用程序。现在,我想重构由useReducer
管理的应用程序状态,并继续使用localStorage
保留数据。
由于涉及许多动人的部分,我很难弄清楚如何重构。如何重构addToCartHandler
中的逻辑以在ADD_TO_CART
情况下使用?从那里开始,我相信我将能够找出cartReducer
中其他情况的模式。谢谢。
https://codesandbox.io/s/goofy-water-pb903?file=/src/App.js
解决方法
这是我的工作。我添加了cartReducer的所有案例,因为我很喜欢它。
如果您想自己动手做,这是第一种使用localStorage保留项目值的设置。
我正在做的概述是:使用切换箱在reducer中设置新状态,然后每次购物车通过效果更改时将localStorage状态设置为新值。
产品中的逻辑只是被简单的动作调度所取代。由于逻辑是在减速器中。在ADD_TO_CART
情况下,您可能可以简化逻辑,但是这可以处理所有事情,并且是一成不变的。使用“沉浸式”之类的东西可以简化逻辑。
const storageKey = "localCart";
const cartReducer = (state,action) => {
switch (action.type) {
case "ADD_TO_CART": {
const product = action.payload;
let index = state.findIndex((item) => product.name === item.name);
if (index >= 0) {
const newState = [...state];
newState.splice(index,1,{
...state[index],quantity: state[index].quantity + 1
});
return newState
} else {
return [...state,{ ...product,quantity: 1 }];
}
}
default:
throw new Error();
}
};
在App
组件中使用:
const [cart,cartDispatch] = useReducer(
cartReducer,[],// So we only have to pull from localStorage one time - Less file IO
(initial) => JSON.parse(localStorage.getItem(storageKey)) || initial
);
useEffect(() => {
// This is a side-effect and belongs in an effect
localStorage.setItem(storageKey,JSON.stringify(cart));
},[cart]);
在Product
组件中使用:
const addToCartHandler = (product) => {
dispatch({ type: "ADD_TO_CART",payload: product });
};
完全正常工作的CodeSandbox
,使用上下文API管理购物车状态
我将从将购物车状态和持久性隔离到本地存储到反应上下文提供者开始。上下文可以为应用程序的其余部分提供购物车状态和操作分配器,并在状态使用效果更新时将状态持久化到localStorage。这将所有状态管理与应用程序分离开来,应用程序只需要使用上下文来访问购物车状态并调度操作以对其进行更新。
import React,{ createContext,useEffect,useReducer } from "react";
import { cartReducer,initializer } from "../cartReducer";
export const CartContext = createContext();
export const CartProvider = ({ children }) => {
const [cart,dispatch] = useReducer(cartReducer,initializer);
useEffect(() => {
localStorage.setItem("localCart",[cart]);
return (
<CartContext.Provider
value={{
cart,dispatch
}}
>
{children}
</CartContext.Provider>
);
};
将应用程序包装在index.js的CartProvider
中
<CartProvider>
<App />
</CartProvider>
完善应用程序的其余部分
在cartReducer
中优化化简器,并导出初始化函数和动作创建器。
const initialState = [];
export const initializer = (initialValue = initialState) =>
JSON.parse(localStorage.getItem("localCart")) || initialValue;
export const cartReducer = (state,action) => {
switch (action.type) {
case "ADD_TO_CART":
return state.find((item) => item.name === action.item.name)
? state.map((item) =>
item.name === action.item.name
? {
...item,quantity: item.quantity + 1
}
: item
)
: [...state,{ ...action.item,quantity: 1 }];
case "REMOVE_FROM_CART":
return state.filter((item) => item.name !== action.item.name);
case "DECREMENT_QUANTITY":
// if quantity is 1 remove from cart,otherwise decrement quantity
return state.find((item) => item.name === action.item.name)?.quantity ===
1
? state.filter((item) => item.name !== action.item.name)
: state.map((item) =>
item.name === action.item.name
? {
...item,quantity: item.quantity - 1
}
: item
);
case "CLEAR_CART":
return initialState;
default:
return state;
}
};
export const addToCart = (item) => ({
type: "ADD_TO_CART",item
});
export const decrementItemQuantity = (item) => ({
type: "DECREMENT_QUANTITY",item
});
export const removeFromCart = (item) => ({
type: "REMOVE_FROM_CART",item
});
export const clearCart = () => ({
type: "CLEAR_CART"
});
在Product.js
中,通过useContext
钩子获取购物车上下文,并分派addToCart
操作
import React,{ useContext,useState } from "react";
import { CartContext } from "../CartProvider";
import { addToCart } from "../cartReducer";
const Item = () => {
const { dispatch } = useContext(CartContext);
...
const addToCartHandler = (product) => {
dispatch(addToCart(product));
};
...
return (
...
);
};
CartItem.js
获取并使用购物车上下文来调度减少数量或移除物品的动作。
import React,{ useContext } from "react";
import { CartContext } from "../CartProvider";
import { decrementItemQuantity,removeFromCart } from "../cartReducer";
const CartItem = () => {
const { cart,dispatch } = useContext(CartContext);
const removeFromCartHandler = (itemToRemove) =>
dispatch(removeFromCart(itemToRemove));
const decrementQuantity = (item) => dispatch(decrementItemQuantity(item));
return (
<>
{cart.map((item,idx) => (
<div className="cartItem" key={idx}>
<h3>{item.name}</h3>
<h5>
Quantity: {item.quantity}{" "}
<span>
<button type="button" onClick={() => decrementQuantity(item)}>
<i>Decrement</i>
</button>
</span>
</h5>
<h5>Cost: {item.cost} </h5>
<button onClick={() => removeFromCartHandler(item)}>Remove</button>
</div>
))}
</>
);
};
App.js
通过上下文挂钩获得购物车状态和调度程序,并更新总商品和价格逻辑以说明商品数量。
import { CartContext } from "./CartProvider";
import { clearCart } from "./cartReducer";
export default function App() {
const { cart,dispatch } = useContext(CartContext);
const clearCartHandler = () => {
dispatch(clearCart());
};
const { items,total } = cart.reduce(
({ items,total },{ cost,quantity }) => ({
items: items + quantity,total: total + quantity * cost
}),{ items: 0,total: 0 }
);
return (
<div className="App">
<h1>Emoji Store</h1>
<div className="products">
<Product />
</div>
<div className="cart">
<CartItem />
</div>
<h3>
Items in Cart: {items} | Total Cost: ${total.toFixed(2)}
</h3>
<button onClick={clearCartHandler}>Clear Cart</button>
</div>
);
}