首页 > 解决方案 > 每当数据库中的数据发生变化时,我们如何更新 react-app 中的 DOM?

问题描述

每当数据库中的数据发生变化时,我们如何更新 react-app 中的 DOM ?

我有场景假设,例如购物应用程序,用户可以在其中购买产品和购买。因此,一旦用户查看单个产品(即单个产品页面)并发现价格为 2000,现在他希望购买该产品并将商品移动到购物车(即购物车页面)。现在我将 DB 中的价格从 2000 更改到 2500 但在购物车页面中我仍然看到旧价格,即 2000。我还使用 redux 来存储购物车项目。所以,总的来说,我的问题是我们如何在不刷新应用程序的情况下在购物车页面中获取更新的价格值?如果我手动或以其他方式更改数据库中的任何值,基本上想实时更新?

SingleProduct.js(页面)

const SingleProduct = ({ product, onStarClick, star }) => {
  const { title, images, slug, description, _id } = product;
  const [tooltip, setTooltip] = useState("Click to Add");

  const dispatch = useDispatch();

  const { user, cart } = useSelector((state) => ({ ...state }));

  const handleAddToCart = () => {
    // create cart Array
    let cart = [];
    if (typeof window !== "undefined") {
      // if cart is in localStorage GET it
      if (localStorage.getItem("cart")) {
        cart = JSON.parse(localStorage.getItem("cart"));
      }
      // push new product to cart
      cart.push({
        ...product,
        count: 1,
      });
      // remove duplicate
      let unique = _.uniqWith(cart, _.isEqual);
      // save to local storage
      localStorage.setItem("cart", JSON.stringify(unique));
      setTooltip("Added");

      // item push into Cart as array of object. Here Suppose price of item is 2000 when it add to redux. Suppose after 2min he decide to go Cart Page during that time price got change in DB from 2000 to 2500. But Redux still have Old price value of item.
      dispatch({
        type: ADD_TO_CART,
        payload: unique,
      });
    }
  };

  return (
    <>
      <div className="col-md-7">
         <Card
          actions={[
            <Tooltip title={tooltip}>
              <a onClick={handleAddToCart}>
                <ShoppingCartOutlined className="text-danger" /> <br /> Add to
                Cart
              </a>
            </Tooltip>,
            <Link to={`/product/${slug}`}>
              <HeartOutlined className="text-info" /> <br />
              Add to Wishlist
            </Link>,
            <RatingModal>
              <StarRating
                name={_id}
                numberOfStars={5}
                rating={star}
                changeRating={onStarClick}
                isSelectable={true}
                starRatedColor="red"
              />
            </RatingModal>,
          ]}
        >
          <ProductListItems product={product} />
        </Card>
      </div>
    </>
  );
};

export default SingleProduct;

Cart.js(页面)

const Cart = ({ history }) => {
  const dispatch = useDispatch();
  
  // Here Cart is getting from Redux. And we want the updated price in cart Array of object if value of price change in DB. But i am still getting 2000 value of price not 2500
  const { user, cart } = useSelector((state) => ({ ...state }));

  const showCartItems = () => (
    <table className="table table-bordered">
      <thead className="thead-light">
        <tr>
          <th scope="col">Image</th>
          <th scope="col">Title</th>
          <th scope="col">Price</th>
          <th scope="col">Brand</th>
          <th scope="col">Color</th>
          <th scope="col">Count</th>
          <th scope="col">Shipping</th>
          <th scope="col">Remove</th>
        </tr>
      </thead>
      {cart.map((p) => (
        <ProductCardInCheckout key={p._id} product={p} />
      ))}
    </table>
  );
  return (
  <div className="col-md-8">
          <h4>Cart / {cart.length} Product</h4>
          {!cart.length ? (
            <p>
              No products in cart. <Link to="/shop">Continue Shopping</Link>
            </p>
          ) : (
            showCartItems()
          )}
        </div>
)
}

标签: javascriptreactjs

解决方案


推荐阅读