我有 data.js 檔案,其中包含有關 T 恤、連帽衫、箱子等的資訊。我在每個陣列中有 5 個物件。如果我在 HomeScreen.js 上呼叫每個陣列,它會顯示陣列包含的所有物件。
如何讓每個陣列在某個頁面上顯示特定數量的物件?例如,在主螢屏中應該顯示 2,但在另一個頁面上應該顯示全部 5。
這是我呼叫 data.js 陣列的表:
<span className="productstitle">Featured T-Shirts</span>
<a href={`/category/tshirts`} className="browseall">All designs ></a>
<table className="maintable">
{data.tshirts.map((product) => (
<Product key={product._id} product={product}></Product>
))}
<p className='featuredtext'><span className="productstitle">Featured Hoodies</span>
<a href={`/category/hoodies`} className="browseall">All designs ></a></p>
{data.hoodies.map((product) => (
<Product key={product._id} product={product}></Product>
))}
<p className='featuredtext'><span className="productstitle">Featured Phone Cases</span>
<a href={`/category/cases`} className="browseall">All designs ></a></p>
{data.cases.map((product) => (
<Product key={product._id} product={product}></Product>
))}
<p className='featuredtext'><span className="productstitle">Featured Pins</span>
<a href={`/category/stickers`} className="browseall">All designs ></a></p>
{data.pins.map((product) => (
<Product key={product._id} product={product}></Product>
))}
<p className='featuredtext'><span className="productstitle">Featured Posters</span>
<a href={`/category/posters`} className="browseall">All designs ></a></p>
{data.posters.map((product) => (
<Product key={product._id} product={product}></Product>
))}
<p className='featuredtext'><span className="productstitle">Featured Mugs</span>
<a href={`/category/mugs`} className="browseall">All designs ></a></p>
{data.mugs.map((product) => (
<Product key={product._id} product={product}></Product>
))}
</table>
uj5u.com熱心網友回復:
您可以嘗試使用.slice(),它會提取陣列的一部分。
例如,對于連帽衫,您可以執行以下操作:
{data.hoodies.slice(0, 2).map((product) => (
<Product key={product._id} product={product}></Product>
))}
如果您只想在主頁中顯示 2 項,則可以在組件的主體中添加條件陳述句(在 jsx 的 return 陳述句之前)。
例如,你可以說..
if (homepage) {
data.hoodies = data.hoodies.slice(0, 2);
}
這有幫助嗎?
uj5u.com熱心網友回復:
使用切片功能
let data = {
tshirts: [{ id: 1, name: 'red'},{ id: 2, name: 'green'},{ id: 3, name: 'blue'},{ id: 4, name: 'orange'},{ id: 5, name: 'yellow'}]
}
data.tshirts.slice(0,3).map((product) => console.log(product))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/455679.html
標籤:javascript 反应
