大家好我正在使用 React 和 materialUI 構建一個克隆服務臺系統當用戶單擊它時,我遇到了從對象數組中刪除特定項目的問題。我曾嘗試使用 updatedRow.splice(index,1) 但這只是刪除添加到數組中的最后一個對象而不是特定對象。我試圖根據 ticketID 屬性刪除它 我嘗試使用數組方法 indexof 來控制臺記錄對象的特定索引,但它只返回 -1,這意味著該項目在屏幕上顯示時不在數組中。該函數應該根據條件是否為真來過濾并僅保留未被選中的項目,并刪除為真的項目,然后應該調用 Setrows 來更新屏幕上的內容。有人可以在這里準確解釋我做錯了什么,請參閱下面的代碼... /// original array to populated with data let row = []; const [rows, setRows] = useState(row); const formDataHandler = ({ desc, option }) => { const data = { description: desc, priority: option, lastUpdate: Date.now(), ticketID:shortid.generate() };setRows([...rows, data]);console.log(rows);};/// delete row function const removeTicket = (index)=> { let updatedRow = rows;// updatedRow.splice(index,1)console.log(updatedRow.filter(index => ticketID !== index.id? ))setRows([...updatedRow])/// returned <Container maxWidth="md"> <Grid> <TableContainer component={Paper}> <Table className={classes.table} aria-label="simple table"> <TableHead> <TableRow> <TableCell>Description</TableCell> <TableCell>Priority</TableCell> <TableCell>Last update</TableCell> <TableCell>Ticket ID</TableCell> </TableRow> </TableHead> <TableBody> {rows.length>0?rows.map((row) => ( <TableRow key={row.ticketID}> <TableCell component="th" scope="row"> {row.description} </TableCell> <TableCell>{row.priority}</TableCell> <TableCell>{row.lastUpdate}</TableCell> <TableCell>{row.ticketID}</TableCell> <TableCell> <IconButton onClick={removeTicket} aria-label="delete" color="primary"> <DeleteIcon /> </IconButton> </TableCell> </TableRow> )):null} </TableBody> </Table> </TableContainer> </Grid> <FormDialog formData={formDataHandler} /> {JSON.stringify(rows)}</Container>);}
從對象數組 Reactjs 中刪除特定項目
蝴蝶刀刀
2023-06-15 16:25:56