单击按钮即可使用 Api 中的数据更新我的 redux 存储

问题描述 投票:0回答:1

我尝试使用按钮更新应用程序的 redux 存储,但每次单击按钮并且映射来自 api 的数据时,它都不会使用预期的值更新存储。

我将预期值(product.title)记录到控制台,然后我注意到它在控制台上出现时几乎立即消失。 我要做的就是留下来

这是我的代码

import { useEffect, useState } from "react";
import "../styles/BestSellers.css";
import { useDispatch } from "react-redux";
import { setItem } from "../features/ProductState";

function BestSellers() {
  const [products, setProducts] = useState([]);
  const [count, setCount] = useState(10);
  const dispatch = useDispatch();

  useEffect(() => {
    fetch(`https://dummyjson.com/products?limit=${count}`)
      .then((res) => res.json())
      .then((data) => {
        setProducts(data.products);
      });
  }, [count]);

  const loadMore = () => {
    setCount((prevCount) => prevCount + 5);
  };

  const handleAction = (product) => {
    dispatch(
      setItem({
        title: product.title,
        image: product.image,
        price: product.price,
      })
    );
  };

  return (
    <div className="container">

      <div className="products">
        {products.map((product) => (
          <a
            onClick={() => {
              handleAction(product);
            }}
            className="link"
            href="/shop"
            key={product.id}
          >
            <div className="product">
              <h5>{product.title}</h5>
              <p>English Department</p>
              <span className="prices">
                <h4 className="discount">$16.48</h4>
                <h4>${product.price}</h4>
              </span>
            </div>
          </a>
        ))}
      </div>

      <button onClick={loadMore} className="btn">
        LOAD MORE PRODUCTS
      </button>
    </div>
  );
}

export default BestSellers;
javascript reactjs redux react-redux
1个回答
0
投票

您正在使用锚标记而不是按钮。锚标记在单击时重新加载页面,并且当页面重新加载时,您的 Redux 存储将重新初始化。不要使用这样的锚标签。

使用

button
元素的示例:

<div className="products">
  {products.map((product) => (
    <button
      key={product.id}
      onClick={() => {
        handleAction(product);
      }}
      className="link"
    >
      <div className="product">
        <h5>{product.title}</h5>
        <p>English Department</p>
        <span className="prices">
          <h4 className="discount">$16.48</h4>
          <h4>${product.price}</h4>
        </span>
      </div>
    </a>
  ))}
</div>
© www.soinside.com 2019 - 2024. All rights reserved.