You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React实现金字塔式产品画廊:动态添加数组元素至Div的报错解决与优化方案

Hey there! Let's break down your problem and fix it properly—using string parsing for React components is definitely not the right approach here, and that's why you're running into issues.

Why Your Current Approach Fails

First, let's unpack the error and why html-react-parser isn't working for you:

  • html-react-parser is designed to parse standard HTML strings, not JSX for custom React components. It has no idea what <Product /> is, so it can't render your component correctly.
  • Your string syntax is invalid for HTML: you're missing quotes around attribute values (e.g., pname = ${product.pname} should be pname="${product.pname}"), which would break parsing even if it could handle React components.
  • The TypeError: product is undefined happens because you don't check if cur stays within the bounds of your products array. If you have fewer than 6 products (1+2+3), cur will exceed the array length and pull an undefined value.

The Proper React Way: Build Component Trees Directly

React's core strength is building UI with component trees—you never need to convert components to strings and parse them. Here's a clean, efficient solution:

Step 1: Rewrite getProducts to Return JSX

Instead of generating strings, return an array of React elements directly:

const getProducts = () => {
  let cur = 0;
  // Generate 3 rows (1, 2, 3 products each)
  return Array.from({ length: 3 }, (_, rowIndex) => {
    const productsInRow = [];
    // Each row has rowIndex + 1 products (0 → 1, 1 → 2, 2 → 3)
    const rowSize = rowIndex + 1;

    for (let i = 0; i < rowSize; i++) {
      // Stop if we run out of products to avoid undefined errors
      if (cur >= products.length) break;
      const product = products[cur++];
      
      productsInRow.push(
        <Product
          key={product.id} // Required for React list rendering
          id={product.id}
          pname={product.pname}
          price={product.price}
          rating={product.rating}
          pic={product.pic}
          altPic={product.altPic}
        />
      );
    }

    return (
      <div key={`product-row-${rowIndex}`} className="product_row">
        {productsInRow}
      </div>
    );
  });
};

Step 2: Render the Components Directly

No parsing needed—just call the function in your JSX:

return (
  // ... your other components
  <div className="product_container">
    <img src={banner} alt="banner" />
    {getProducts()}
  </div>
  // ... your other components
);

Why This Is Better

  • React-native: This follows React's intended pattern, so you avoid weird parsing bugs and compatibility issues.
  • Safe: The boundary check (if (cur >= products.length) break) prevents product is undefined errors if your product list is shorter than 6 items.
  • Clean: No messy string concatenation, and you get proper JSX syntax highlighting and type checking (if using TypeScript).
  • Performant: React can optimize component rendering properly when you pass real elements instead of parsing strings.

内容的提问来源于stack exchange,提问作者Nrook 301

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 04:42:46