我有一個元素串列,我想在每一行的卡片中列印其中的 3 個。
以下代碼的問題:它只列印前兩個元素并且回圈停止。
這是我使用 reactjs 和 mui 的代碼:
const testList = [//my list]
const ListInvoices = (props) => {
const invoicesList = () => {
for(let i = 1; i <= testList?.length; 3*i){
let invList = testList?.slice(i-1, 2*i)
return(
<Grid container alignItems="center" justifyContent="center">
<div style={{ display: "flex", flexDirection: "row" }}>
{invList ?.map((elt, index) => {
return(
<Grid item>
<Card sx={{m: 2}} key={{index}}>
{/* content of card */}
</Card>
</Grid>
)
})
}
</div>
</Grid>
)
}
}
return(
<Box sx={{ backgroundColor: "#f6f6f6" }} pt={4} pb={4}>
<Container maxWidth="lg">
{invoicesList()}
</Container>
</Box>
)
}
編輯:正如答案所建議的,我改變了這個
for(let i = 1; i <= testList?.length; i*3)
//..
let invList= testList?.slice(i-1, 2*i)
對此
for(let i = 1; i <= testList?.length; i 3)
//..
let invList = testList?.slice(i-1, 3*i)
但問題始終存在
先感謝您
uj5u.com熱心網友回復:
這是您的問題 Loop inside React JSX的相關資訊 但是問題可能是當您將 i 乘以 3 時,
for(let i = 1; i <= testList?.length; 3*i <-- here
因為當i = 1時,i * 3 = 3,而當i = 3時,i * 3 = 9,所以會跳過第二行。
uj5u.com熱心網友回復:
編輯
看到你的問題依舊存在,再次閱讀你的代碼后,我看到了一個我一開始沒有注意到的小細節。你的 for 回圈作業正常嗎?我嘗試過使用 RunJS,它一遍又一遍地創建無限回圈。
當您執行 i*3 時,您并沒有真正更新 i 的值,而是進行了一個沒有進一步影響的簡單宣告。讓我知道這是否有意義,但這將是更正后的代碼:
for(let i = 1; i <= testList.length; i = i 3) {
原始答案
我不確定我是否解決了您的問題。但是,我確實明白為什么這條線
invList ?.map((elt, index) => {
僅回傳 2 張卡。我假設它在這里必須回傳 3?如果是這樣,也許我有一個答案給你。
請注意,使用切片時,將不包括結束索引。
應用以下代碼(從您的代碼中提取)時:
let invList = testList?.slice(i-1, 2*i)
如果 index 為 1 并且我們有一個陣列,如下所示:
[0, 1, 2, 3, 4, 5]
invList 將從 0 (index - 1) 切片到 1,因為 2 (2 * 1) 將是不包括在內的結束索引。
因此,應列印第三個數字,并進行以下小改動:
let invList = testList?.slice(i-1, 3*i)
或者
let invList = testList?.slice(i-1, 2*i 1)
話雖如此,您使用 for 回圈是否有任何具體原因?我相信它可以用 map 替換,使用在每次迭代時傳遞的第二個引數(索引引數)。
uj5u.com熱心網友回復:
好吧,我的一個朋友給了我一個簡單的解決方案來實作我想要的,而且@Andy 還建議使用 mui Grid 的道具。所以這是解決方案的代碼
const testList = [//my list]
const ListInvoices = (props) => {
return(
<Box sx={{ backgroundColor: "#f6f6f6" }} pt={4} pb={4}>
<Container maxWidth="lg">
<Grid container spacing={2} alignItems="center" justifyContent="center">
{testList?.map((elt, index) => {
return (
<Grid item xs={4}>
<Card sx={{m: 2}} key={{index}}>
{/*content*/}
</Card>
</Grid>
);
})
}
</Container>
</Box>
)
}
因此,通過給網格中的每個專案 xs=4 (12/4 = 3) 在每行中列印 3 張卡片并為接下來的 3 個專案回傳新行,依此類推..
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/526646.html
