React中映射生成的编辑按钮触发无限重渲染问题求助
React 无限重渲染问题解决
问题说明
我是React新手,通过API获取用户数据并生成表格,想给每行添加编辑按钮,点击后在模态框表单中编辑用户。但点击按钮时将用户对象传入handleEditShow函数,出现错误:
"Too many re-renders. React limits the number of renders to prevent an infinite loop."
错误原因
核心问题出在编辑按钮的onClick绑定方式:
<Button variant="secondary" id={item.id} onClick={handleEditShow(item)}>Edit</Button>
这里直接调用了handleEditShow(item),会在组件每次渲染时立即执行函数,而非点击按钮时触发。函数内调用setShowEdit和setEditUser会触发组件重新渲染;重新渲染时又会再次执行handleEditShow(item),反复触发状态更新与渲染,最终导致无限循环。
另外,handleEditShow里的setEditUser({person: ""})没有将待编辑用户对象存入状态,不符合业务需求。
修复方案
- 修改
onClick绑定逻辑:用箭头函数包裹,确保只有点击按钮时才执行handleEditShow并传入当前用户对象。 - 修正
handleEditShow的状态更新逻辑:将传入的用户对象存入editUser状态,让表单能获取到正确的编辑数据。 - 调整状态初始化值:
editUser初始设为null或空对象,更贴合业务场景。
修正后的完整代码
状态与处理函数部分
const [showEdit, setShowEdit] = useState(false); const [editUser, setEditUser] = useState(null); // 初始化为null更合理 const handleEditShow = (user) => { console.log(user); setEditUser(user); // 存入当前要编辑的用户对象 setShowEdit(true); }; const handleEditClose = () => { setShowEdit(false); setEditUser(null); // 关闭模态框时清空编辑状态 };
表格部分(仅修改按钮区域)
<Table striped> <thead> <tr> <th>Name</th> <th>Login</th> <th>Last Active</th> <th>Email</th> <th>Supervisor</th> <th>Active</th> <th>Language</th> <th>Edit</th> </tr> </thead> <tbody> {users.person && users.person.map((item) => ( <tr key={item.id}> <td>{item.name}</td> <td>{item.login}</td> <td>{item.lastActive}</td> <td>{item.email}</td> <td>{item.supervisor}</td> <td>{item.active}</td> <td>{item.language}</td> <td> {/* 用箭头函数包裹,点击时才执行handleEditShow */} <Button variant="secondary" id={item.id} onClick={() => handleEditShow(item)}> Edit </Button> </td> </tr> ))} </tbody> </Table>
模态框部分
<Modal show={showEdit} onHide={handleEditClose}> <Modal.Header closeButton> <Modal.Title>User Editor</Modal.Title> </Modal.Header> <Modal.Body> {/* 只有editUser存在时才渲染表单,避免空值问题 */} {editUser && <EditForm user={editUser} />} </Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={handleEditClose}> 取消 </Button> </Modal.Footer> </Modal>
内容的提问来源于stack exchange,提问作者rlatmfrl
相关产品推荐
相关产品推荐

