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-parseris 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 bepname="${product.pname}"), which would break parsing even if it could handle React components. - The
TypeError: product is undefinedhappens because you don't check ifcurstays within the bounds of yourproductsarray. If you have fewer than 6 products (1+2+3),curwill 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) preventsproduct is undefinederrors 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
相关产品推荐
相关产品推荐

