首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用useReducer持久化localStorage

问使用useReducer持久化localStorage
EN

Stack Overflow用户
提问于 2020-10-27 09:11:31
回答 2查看 3.6K关注 0票数 4

我有一个使用useState的迷你购物车应用程序。现在,我希望重构应用程序的状态,使其由useReducer管理,并继续使用localStorage持久化数据。

我很难弄清楚如何重构,因为涉及到许多移动的部分。如何将addToCartHandler中的逻辑重构为在ADD_TO_CART用例中使用?从那时起,我相信我将能够弄清楚cartReducer中其他情况的模式。谢谢。

https://codesandbox.io/s/goofy-water-pb903?file=/src/App.js

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-10-27 12:09:58

使用上下文API管理购物车状态

首先,我会将购物车状态和持久化隔离到一个react上下文提供程序的本地存储。上下文可以向应用程序的其余部分提供购物车状态和操作分派器,还可以在使用效果更新状态时将状态持久化到localStorage。这将所有的状态管理从应用程序中解耦出来,应用程序只需要使用上下文来访问购物车状态并调度操作来更新它。

代码语言:javascript
复制
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", JSON.stringify(cart));
  }, [cart]);

  return (
    <CartContext.Provider
      value={{
        cart,
        dispatch
      }}
    >
      {children}
    </CartContext.Provider>
  );
};

在index.js中将应用程序包装在CartProvider中

代码语言:javascript
复制
<CartProvider>
  <App />
</CartProvider>

​

​

完善应用程序的其余部分

在cartReducer中,优化reducer,并导出初始化器函数和操作创建器。

代码语言:javascript
复制
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操作

代码语言:javascript
复制
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获取并使用购物车上下文分派活动以减少数量或删除项目。

代码语言:javascript
复制
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通过上下文钩子获取购物车状态和dispatcher,并更新商品总数和价格逻辑以说明商品数量。

代码语言:javascript
复制
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>
  );
}
票数 11
EN

Stack Overflow用户

发布于 2020-10-27 10:29:09

这是我的工作。我为cartReducer添加了所有的案例,因为我觉得它很有趣。

如果您想自己解决这个问题,这里是使用localStorage保存项目值的设置的第一个例子。

我正在做的概述是:使用开关案例在reducer中设置新状态,然后在每次购物车通过效果更改时将localStorage状态设置为新值。

产品中的逻辑只是替换为一个简单的操作分派。因为逻辑是在减法器中。您可能会简化ADD_TO_CART中的逻辑,但它以一种不可变的方式处理所有事情。使用像immer这样的东西可以将逻辑简单化一点。

代码语言:javascript
复制
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组件中使用:

代码语言:javascript
复制
  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组件中使用:

代码语言:javascript
复制
  const addToCartHandler = (product) => {
    dispatch({ type: "ADD_TO_CART", payload: product });
  };

完整的工作CodeSandbox

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64547044

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档