如何制作一个在页面之间更新数据的 React Hooks

发布于 2025-01-11 02:19:34 字数 1359 浏览 0 评论 0原文

我正在尝试创建一个自定义挂钩来存储购物车数据。

购物车对象:

{ uid:Quantity, uid2:Quantity2, ...}

我所做的 Hook:

import { useState } from "react";

// Return a new object without empty values
const clean = (obj) =>
  Object.keys(obj).reduce((acc, key) => {
    if (obj[key]) {
      acc[key] = obj[key];
    }
    return acc;
  }, {});

export const useCart = () => {
  // Cart is [uid]=quantity
  const [cart, setCart] = useState({});

  const updateCart = ({ uid = 0, quantity = 1 }) => {
    const newCart = clean({
      ...cart,
      [uid]: quantity > 0 ? quantity : null
    });

    setCart(newCart);
    console.log(" New Cart : ", JSON.stringify(newCart));
  };

  // Do are they reactive ? Or do we need to useState them
  const count = Object.values(cart).reduce((acc, value) => acc + value, 0);

  // Return all
  return { cart, updateCart, setCart, count };
};

我遇到的问题

购物车正常工作对于单个项目来说很好,但是当我更新 DOM 并重新请求购物车数据时,它们又回到了初始值。

我很确定这是因为 updateCart() 是用初始值初始化的,但没有更新......但我不知道该怎么做?

我还尝试在组件上直接使用 setCart() 而不是 updateCart() 但没有更好的。

我做了一个例子来测试它没有我的项目: https://codesandbox.io/s/reverent -tess-8pymji

谢谢。

I'm trying to create a custom hooks in order to store Cart data.

The cart object:

{ uid: quantity, uid2: quantity2, ...}

The Hook I did:

import { useState } from "react";

// Return a new object without empty values
const clean = (obj) =>
  Object.keys(obj).reduce((acc, key) => {
    if (obj[key]) {
      acc[key] = obj[key];
    }
    return acc;
  }, {});

export const useCart = () => {
  // Cart is [uid]=quantity
  const [cart, setCart] = useState({});

  const updateCart = ({ uid = 0, quantity = 1 }) => {
    const newCart = clean({
      ...cart,
      [uid]: quantity > 0 ? quantity : null
    });

    setCart(newCart);
    console.log(" New Cart : ", JSON.stringify(newCart));
  };

  // Do are they reactive ? Or do we need to useState them
  const count = Object.values(cart).reduce((acc, value) => acc + value, 0);

  // Return all
  return { cart, updateCart, setCart, count };
};

The issue I have

The cart works fine for a single Item but when I update the DOM and re-ask for cart data, they're it's back to initial value.

I'm pretty sure it's because the updateCart() is initialized with initial value who isn't updated... but I don't know how to do it ?

I also tried to use directly setCart() on components instead of updateCart() but nothing better.

I did an example to test it without my project: https://codesandbox.io/s/reverent-tess-8pymji

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小ぇ时光︴ 2025-01-18 02:19:34

问题是每次路由改变时,它都会重新初始化你的 React hook,并且也会重新初始化该 hook 上的状态。

您可能希望将自定义挂钩创建为单例,以便它可以在不同路由上的多个组件之间共享状态。

react-singleton-hook< /strong> 是一个非常简洁的库,您可以使用它来做到这一点。

您必须稍微更新一下钩子的实现:

import { useState } from "react";
import { singletonHook } from "react-singleton-hook";

// Return a new object without empty keys
const clean = (obj) =>
  Object.keys(obj).reduce((acc, key) => {
    if (obj[key]) {
      acc[key] = obj[key];
    }
    return acc;
  }, {});

export const useCartImpl = () => {
  // Cart is [uid]=quantity
  const [cart, setCart] = useState({});
  const updateCart = ({ uid = 0, quantity = 1 }) => {
    const newCart = clean({
      ...cart,
      [uid]: quantity > 0 ? quantity : null
    });

    setCart(newCart);
    console.log(" New Cart : ", JSON.stringify(newCart));
  };

  // Do are they reactive ? Or do we need to useState them
  const count = Object.values(cart).reduce((acc, value) => acc + value, 0);

  // Return all
  return { cart, updateCart, setCart, count };
};

export const useCart = singletonHook({}, useCartImpl);

这里有一个更新CodeSandbox供您参考。

The problem is that every time the route changes, it will reinitialise your React hook and that will also reinitialise the state on that hook.

You probably are looking to create your custom hook as a Singleton so that it could share the state across multiple components on different routes.

react-singleton-hook is a really neat library that you can use in order to do just that.

You'll have to update the implementation of your hook a bit:

import { useState } from "react";
import { singletonHook } from "react-singleton-hook";

// Return a new object without empty keys
const clean = (obj) =>
  Object.keys(obj).reduce((acc, key) => {
    if (obj[key]) {
      acc[key] = obj[key];
    }
    return acc;
  }, {});

export const useCartImpl = () => {
  // Cart is [uid]=quantity
  const [cart, setCart] = useState({});
  const updateCart = ({ uid = 0, quantity = 1 }) => {
    const newCart = clean({
      ...cart,
      [uid]: quantity > 0 ? quantity : null
    });

    setCart(newCart);
    console.log(" New Cart : ", JSON.stringify(newCart));
  };

  // Do are they reactive ? Or do we need to useState them
  const count = Object.values(cart).reduce((acc, value) => acc + value, 0);

  // Return all
  return { cart, updateCart, setCart, count };
};

export const useCart = singletonHook({}, useCartImpl);

Here's an Update CodeSandbox for your ref.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文