简体   繁体   English

在 React 中删除和复制数组元素

[英]Deleting and copying array elements in React

I have been tasked to add a copy and delete button on one of our tables.我的任务是在我们的一张桌子上添加一个复制和删除按钮。 I am trying to pass the index from the map to the delete and copy onclick and this does delete but...我正在尝试将索引从地图传递到删除并复制 onclick,这确实删除了但是...

Problem: If you copy a row it will have the exact same "i" as the original, and it moves the position of all the ones below it messing up the delete tremendously问题:如果您复制一行,它将具有与原始行完全相同的“i”,并且它会移动其下方所有行的位置,从而极大地破坏了删除

I was under the impression that if I setRows() to something new it would run the mapping again and give them all the correct i's in each function but this doesn't seem to be the case, why?我的印象是,如果我将 setRows() 设置为新的东西,它会再次运行映射并在每个函数中为它们提供所有正确的 i,但情况似乎并非如此,为什么?

const AdvancedTable = () => {
    const [rows, setRows] = useState(tableRows); ///tableRows is basically an array of divs
    const deleteOnClick = (i: number) => {
        setRows(() => {
            const myRows = [...rows];
            myRows.splice(i, 1);
            return myRows;
        });
    }
    const copyOnClick = (i: number) => {
        setRows(() => {
            const myRows = [...rows];
            myRows.splice(i, 0, rows[i]);
            return myRows;
        });
    }
    return (

            <Paper>
                     {
                         rows.map((row: any, i: number) => (
                                     <div>
                                         <IconButton onClick={() => { deleteOnClick(i) }} size="small">
                                             <ClearIcon />
                                         </IconButton>
                                         <IconButton onClick={() => { copyOnClick(i) }} size="small">
                                             <FileCopyIcon />
                                         </IconButton>
                                     </div>
                                 </TableCell>
                                 {row}

                         ))}
            </Paper>
    );
}
export default AdvancedTable;

Do you want the copy method to copy the row below the one you clicked or to send it to then end of the array?您是否希望复制方法复制您单击的行下方的行或将其发送到数组的末尾?

maybe this can help you assuming you can call the i value from your row object with .i也许这可以帮助您假设您可以使用 .i 从行对象中调用 i 值

const copyOnClick = (i: number) => {
    setRows(() => {
        const myRows = [...rows];
        // send the new row to the end of the array
        myRows.splice(rows.length, 0, rows[i]);
        // change the new row i value to + 1 of the last object that was previously in the array
        myRows[myRows.pop().i].i = rows.pop().i + 1
        return myRows;
    });
}

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

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