繁体   English   中英

ReactJS、function 仅在两次单击后工作

[英]ReactJS, function only working after two clicks

我知道这是一个常见的问题,因为 react hook 更新的异步特性,我已经看到有一些类似的问题。 但是我不知道如何使这项工作。

我有一个空的对象数组(购物车),当在特定产品上单击 addToCart 时,需要使用有关该产品的所有数据创建一个新的 object。 第一次点击,只得到一个空的object。 从第二次开始,一切似乎都奏效了。

大批:

 const [cartArray, setCartArray] = useState([
    { imgUrl: "", nameUrl: "", priceUrl: "", id: "" },
  ]);

然后在这里作为道具传递,其中有 addToCart function 和触发它的点击事件:

const Product = ({
  imgUrl,
  nameUrl,
  priceUrl,
  id,
  description,
  cartArray,
  setCartArray,
  productArray,
}) => {
  const [title, setTitle] = useState("");
  const [productId, setProductId] = useState("");
  const [price, setPrice] = useState("");
  const [img, setImg] = useState("");
  const [modalClassName, setModalClassName] = useState("hidden");

  const addToCart = () => {
    setCartArray((prev) => [
      {
        imgUrl: imgUrl,
        nameUrl: nameUrl,
        priceUrl: priceUrl,
        id: id,
      },
      ...prev,
    ]);
  };

  return (
    <div className="product">
      <div className="img-container">
        <img src={imgUrl} alt="product image" />
      </div>
      <div className="product-description">
        <p>{nameUrl}</p>
        <h3>€ {priceUrl}</h3>
      </div>
      <div className="button-container">
        <AddShoppingCartIcon
          className="btn btn-add-to-cart"
          onClick={addToCart}
        />
        <FavoriteBorderIcon className="btn btn-favorite" />
      </div>
    </div>
  );
};

这里是 Product 组件的渲染位置:

const ProductContainer = ({
  productArray,
  setProductArray,
  showNavBar,
  cartArray,
  setCartArray,
}) => {
  useEffect(() => {
    axios
      .get("https://fakestoreapi.com/products")
      .then((res) => setProductArray(res.data));

    console.log(productArray);
  }, []);

  return (
    <div className="product-container-parent" id="shop" onScroll={showNavBar}>
      <div className="product-container-header">
        <h1>New Arrivals</h1>
      </div>
      <div className="product-container">
        {productArray.map((e) => {
          return (
            <Product
              imgUrl={e.image}
              nameUrl={e.title}
              priceUrl={e.price}
              id={e.id}
              description={e.description}
              cartArray={cartArray}
              setCartArray={setCartArray}
              productArray={productArray}
            />
          );
        })}
      </div>
    </div>
  );
};

有任何想法吗? 谢谢!

The initial state for cartArray seems to be having an empty obj { imgUrl: "", nameUrl: "", priceUrl: "", id: "" } The addToCart function appends the new object to the cartArray . 所以你会得到空的 object 作为第一个渲染的。 我建议将 cartArray 的初始cartArray设置为空数组。

const [cartArray, setCartArray] = useState([]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM