reactjs 是否可以只更新map()中的“查看更多”?

hmae6n7t  于 2023-04-11  发布在  React
关注(0)|答案(2)|浏览(105)

我正在实践一个使用React.js作为前端框架来显示产品的项目。我试图通过product_type过滤产品。当获取数据时,我使用slice()在每个类别上显示3个产品,然后如果类别中的产品超过3个,单击“查看更多”按钮,它将显示3个产品。
它是任何方法,只是显示另一个3产品在特定类别?现在,当我点击按钮,每个类别正在加载3多个产品。
任何和所有的反馈都很感激。谢谢!
App.js

import { useEffect, useState } from "react";
import axios from "axios";

import "./styles.css";
import Product from "./Product";

export default function App() {
  const [products, setProducts] = useState([]);
  const [productSlice, setProductSlice] = useState(3);

  useEffect(() => {
    axios
      .get("https://www.allbirds.com/products.json?limit=50")
      .then((response) => {
        // All products return as an array of product objects
        const { products } = response.data;

        setProducts(products);
      });
  }, []);

  return (
    <div className="App">
      <div>
        {categories.map((cat, i) => (
          <>
            <div>
              <h5 key={i}>{cat}</h5>

              {products
                .filter((type) => type.product_type === cat)
                .slice(0, productSlice)
                .map((product) => (
                  <Product data={product} />
                ))}
            </div>
            <p>
              Total in {cat} :
              {products.filter((type) => type.product_type === cat).length}
            </p>

            <button
              onClick={() => {
                // console.log("This is",cat);
                products.filter((type) => type.product_type === cat).length >
                  2 && setProductSlice(productSlice + 1);
              }}
            >
              See more
            </button>
          </>
        ))}
      </div>

      
    </div>
  );
}

Products.js

export default function Product({ data }) {
  

  const { images, title, handle } = data;

  return (
    <div key={handle}>
      <h2>{title.split("-")[0]}</h2>
      <div>
        <img src={images[0].src} style={{ width: "100px" }} alt={handle} />
      </div>
    </div>
  );
}
bfnvny8b

bfnvny8b1#

由于您希望在不同类别中显示不同数量的产品,因此您可以定义一个状态productSlices来表示这些产品计数。
productSlices的初始值为

{
  Shoes: 3,
  Apparel: 3,
  Socks: 3
}

例如,当你点击Shoes类别中的按钮时,productSlices.Shoes的值变为4,其余的值保持为3。在Map操作中,你使用productSlices[cat]来获取该类别中应该显示多少产品。
你可以这样修改你的代码:

import { useEffect, useState } from "react";
import axios from "axios";

import "./styles.css";
import Product from "./Product";

export default function App() {
  const categories = ["Shoes", "Apparel", "Socks"];
  const [products, setProducts] = useState([]);
  
  const [productSlices, setProductSlices] = useState(
    categories.reduce((a, v) => ({ ...a, [v]: 3 }), {})
  );
  
  useEffect(() => {
    axios
      .get("https://www.allbirds.com/products.json?limit=50")
      .then((response) => {
        // All products return as an array of product objects
        const { products } = response.data;

        console.log(products);
        setProducts(products);
      });
  }, []);

  return (
    <div className="App">
      <div>
        {categories.map((cat, i) => (
          <>
            <div>
              <h5 key={i}>{cat}</h5>

              {products
                .filter((type) => type.product_type === cat)
                .slice(0, productSlices[cat])
                .map((product) => (
                  <Product data={product} />
                ))}
            </div>
            <p>
              Total in {cat} :
              {products.filter((type) => type.product_type === cat).length}
            </p>

            <button
              id={cat}
              onClick={() => {
                setProductSlices({
                  ...productSlices,
                  [cat]: productSlices[cat] + 1
                });
              }}
            >
              See more
            </button>
          </>
        ))}
      </div>
    </div>
  );
}
tct7dpnv

tct7dpnv2#

您需要一个专用的函数,将与您的数据需要工作。这可以在数据第一次加载后,从API获取或当按钮被点击要求更多的数据。
建议您在将数据传递给组件之前先处理这些数据。这样,通过应用关注点分离,而不是在组件上执行所有转换/逻辑,您将拥有更具可读性/更清晰的代码。尽量使复杂的代码远离按钮、div、组件等
我的建议是:

const [products, setProducts] = useState([]); //will contains the remote data
     const [productSlice, setProductSlice] = useState([]); //will contains the current visible slice

     const [sliceStart, setSliceStart] = useState(0);

     const pageSize = 3;

     const updateSlice = useCallback(() => {

          const hasMore = products.length > currentIndex;

          if (hasMore) {

              //here we get the copy from products

               const end = sliceStart + pageSize;
               const nextItems = products.slice(sliceStart, end);

               setProductSlice( old => [...old, ...nextItems]);
           }
     }, [products, sliceStart]);

     useEffect(() => {

        const fetchData = async () => {
            const response = await axios.get("https://www.allbirds.com/products.json?limit=50");

            // All products return as an array of product objects
            const { products } = response.data;

            setProducts(products);
         }

         fetchData().catch(err => console.error(err));

      }, [updateSlice]);

      return (
          <>

              <button
              onClick={() => setSliceStart(prev => prev + pageSize)}>
                  See more
            </button>

          </>
      )

希望能帮到你

相关问题