简体   繁体   English

从对象数组中删除特定项目 Reactjs

[英]Remove a specific item from an array of objects Reactjs

Hi All i am building a clone service desk system using React and materialUI I am having issues with removing specific items from an array of objects when the user clicks on it.大家好,我正在使用 React 和 materialUI 构建一个克隆服务台系统,当用户单击它时,我遇到了从对象数组中删除特定项目的问题。 I have tried to use updatedRow.splice(index,1) but this just removes the last object added to the array and not a specific object.我尝试使用 updatedRow.splice(index,1) 但这只是删除了添加到数组中的最后一个 object 而不是特定的 object。 I am trying to remove it based on the ticketID property I have tried to use the array method indexof to console log the specific index of the object but it just returns -1 meaning the item is not in the array when its displaying on the screen.我试图根据ticketID 属性删除它我尝试使用数组方法indexof 来控制台记录object 的特定索引,但它只返回-1,表示该项目在屏幕上显示时不在数组中。 The function should filter and only keep the items which havent been selected based on if the condition is true and remove what is true then should call Setrows to update what is on the screen. function 应过滤并仅根据条件是否为真保留未选择的项目并删除为真的项目,然后应调用 Setrows 更新屏幕上的内容。 Could someone explain exactly what I am doing wrong here see code below...有人可以在这里准确解释我做错了什么,请参见下面的代码...

 /// 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>
);
}

You need to pass the ticketID to your IconButton 's onClick handler:您需要将ticketID传递给IconButtononClick处理程序:

<IconButton 
  onClick={() => removeTicket(row.ticketID)} 
  aria-label="delete" 
  color="primary"
>
  <DeleteIcon />
</IconButton>

And update your handler where you can create a new array using the .filter() method:并更新您的处理程序,您可以在其中使用.filter()方法创建一个新数组:

const removeTicket = (ticketID)=> {
  setRows(rows.filter(item => ticketID !== item.ticketID)
}

This rows.filter() returns every element where the ticketID is not the same as the one you passed down.这个rows.filter()返回每个ticketID与您传递的不同的元素。

If you know index that will be removed you can use Array.prototype.slice and the logic is disconsider the element at index.如果您知道将被删除的索引,您可以使用Array.prototype.slice并且逻辑是不考虑索引处的元素。

So, you will have to add the index as second param in your map function and change the onClick on IconButton to () => removeTicket(index) .因此,您必须将index添加为 map function 中的第二个参数,并将onClick上的IconButton更改为() => removeTicket(index)

Your remove function will contains the following snippet:您的删除 function 将包含以下代码段:

setRows(prevRows => [
  ...prevRows.slice(0, index),
  ...prevRows.slice(index + 1)
]);

If you need the ticketId to make a call to an api you can get it through index rows[index] or by passing it in the onClick function () => removeTicket(row.ticketID, index)如果您需要 ticketId 来调用 api,您可以通过索引rows[index]或通过将其传递给 onClick ZC1C425268E68385D1AB5074C17A94F14TicketIDrow () => removeTicket(row.ticketID, index)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM