React.js实现表格行删除功能遇异常,如何正确修复?
问题原因
- 你声明的
row1是组件内的普通全局变量,每次调用increaseRow时没有清空之前的残留值,多次添加行后会生成重复的行ID,而你的删除逻辑是按ID过滤,重复ID会导致删除逻辑异常,出现删不掉或者一次删多行的问题。 - 新增行的ID生成逻辑和初始默认行的ID没有衔接,容易出现ID冲突。
- 未对输入为空的边界场景做处理,用户未输入就点击添加按钮会触发NaN错误。
修复后完整代码
import { useState } from "react"; import Table from "react-bootstrap/Table"; import './App.css' const App = () => { const [row, setRow] = useState(""); // 初始行ID从1开始,后续新增ID接在最大ID之后,避免重复 const [NewRow, setNewRow] = useState([1,2,3,4,5]); const addRow = (e) => { e.preventDefault(); setRow(e.target.value); }; const increaseRow = () => { const addCount = parseInt(row) || 0; if (addCount <= 0) return; // 每次新增行都创建新的临时数组,避免旧值残留 const newRowIds = []; // 取现有行的最大ID,后续ID从最大值+1开始生成,保证唯一 const maxId = Math.max(...NewRow); for (let i = 1; i <= addCount; i++) { newRowIds.push(maxId + i); } setNewRow([...NewRow, ...newRowIds]); // 清空输入框 setRow(""); }; const deleteRow = (id) => { const updatedRows = NewRow.filter((rowId) => rowId !== id); setNewRow(updatedRows); }; return ( <> <div> <form> <input type="number" min="1" value={row} onChange={addRow} placeholder="Enter Number Of Row's" /><br /> </form> <button onClick={increaseRow}> Add </button> </div> <div className="container"> <form > <Table striped bordered hover responsive variant="light"> <thead> <tr> <th> {" "} <h6> No. </h6>{" "} </th> <th> {" "} <h6> Injection Speed </h6>{" "} </th> <th> {" "} <h6> Fill Time </h6>{" "} </th> <th> {" "} <h6> Peak Inj Press </h6>{" "} </th> <th> {" "} <h6> Viscocity </h6>{" "} </th> <th> {" "} <h6> Shear Rate </h6>{" "} </th> <th> {" "} <h6> AbsoluteDropViscocity </h6>{" "} </th> <th> {" "} <h6> %DropViscocity </h6>{" "} </th> <th> {" "} <h6> Action </h6>{" "} </th> </tr> </thead> <tbody className="grid_style"> {NewRow.map((rowId) => { return ( <tr key={rowId}> <td> {rowId} </td> <td> <input type="text" className="form-control" /> </td> <td> <input type="text" className="form-control" /> </td> <td> <input type="text" className="form-control" /> </td> <td> <input type="text" className="form-control" readOnly /> </td> <td> <input type="text" className="form-control" readOnly /> </td> <td> <input type="text" className="form-control" readOnly /> </td> <td> <input type="text" className="form-control" readOnly /> </td> <td> <i className="fa fa-trash viscocity_icons" onClick={() => deleteRow(rowId)} > </i> </td> </tr> ); })} </tbody> </Table> </form> </div> </> ); }; export default App;
主要改动点
- 移除了冗余的
row1全局变量、allRowsAdded状态,每次新增行时动态计算现有行的最大ID,生成连续不重复的新ID,彻底避免ID冲突。 - 每次新增行都创建全新的临时数组存储新ID,不存在旧值残留问题。
- 将输入框类型改为
number并添加min="1"限制,增加输入校验,避免空输入、非法输入导致的报错。 - 新增行完成后自动清空输入框,优化使用体验。
- 删除逻辑中去掉了不必要的数组拷贝,直接对原状态数组过滤即可。
内容的提问来源于stack exchange,提问作者suraj vishwakarma
相关产品推荐
相关产品推荐

