React Hooks问题:编辑后如何更新列表中的项?
解决React Hooks CRUD应用的编辑更新问题
要实现编辑后的更新操作,你需要添加一个状态追踪当前编辑项的ID,同时修改提交逻辑区分「添加新项」和「更新现有项」模式,具体实现如下:
1. 添加编辑状态
新增editingItemId状态,标记当前是否处于编辑模式及对应项的ID:
const [editingItemId, setEditingItemId] = useState<number | null>(null);
2. 修改编辑函数
点击编辑按钮时,除了填充输入框,还要记录当前编辑项的ID:
const editItem = (item: any) => { setFile(undefined); setComment(item.comment); setAmount(item.amount); // 记录当前编辑项ID,进入编辑模式 setEditingItemId(item.id); };
3. 重构提交逻辑
修改提交函数,根据editingItemId判断执行添加或更新操作:
const handleSubmit = (e: any) => { e.preventDefault(); if (editingItemId !== null) { // 编辑模式:更新对应项 const updatedItems = items.map(item => item.id === editingItemId ? {...item, comment, amount} : item ); setItems(updatedItems); // 退出编辑模式 setEditingItemId(null); } else { // 添加模式:新增项 const newItem = { id: new Date().getTime(), comment: comment, amount: amount, preview: preview }; setItems([...items, newItem]); } // 重置输入框状态 setFile(null); setComment(""); setAmount(""); };
4. 调整按钮显示与绑定
修改按钮文本,根据模式切换显示「Add」或「Update」,并绑定新的提交函数:
<button onClick={handleSubmit}> {editingItemId !== null ? "Update" : "Add"} </button>
完整修改后的代码
import { useState } from 'react'; const CRUDComponent = () => { const [items, setItems] = useState<any>([]); const [comment, setComment] = useState(""); const [amount, setAmount] = useState(""); const [file, setFile] = useState<any>(null); const [preview, setPreview] = useState<any>(null); const [editingItemId, setEditingItemId] = useState<number | null>(null); const handleSubmit = (e: any) => { e.preventDefault(); if (editingItemId !== null) { const updatedItems = items.map(item => item.id === editingItemId ? {...item, comment, amount} : item ); setItems(updatedItems); setEditingItemId(null); } else { const newItem = { id: new Date().getTime(), comment: comment, amount: amount, preview: preview }; setItems([...items, newItem]); } setFile(null); setComment(""); setAmount(""); }; const editItem = (item: any) => { setFile(undefined); setComment(item.comment); setAmount(item.amount); setEditingItemId(item.id); }; const deleteItem = (id: any) => { const updatedItems = [...items].filter((item) => item.id !== id); setItems(updatedItems); }; return ( <div> {items.map((item: any) => ( <div key={item.id}> <div>{item.comment}</div> <div>{item.amount} $</div> <div onClick={() => editItem(item)}>Edit</div> <div onClick={() => deleteItem(item.id)}>Delete</div> </div> ))} <input value={comment} onChange={(e) => setComment(e.target.value)} placeholder="Comment" /> <input value={amount} onChange={(e) => setAmount(e.target.value)} type="number" /> <button onClick={handleSubmit}> {editingItemId !== null ? "Update" : "Add"} </button> </div> ); }; export default CRUDComponent;
关键说明
- 用
editingItemId区分模式:非null时为编辑模式,执行更新逻辑;null时为添加模式,执行新增逻辑。 - 更新项时通过
map遍历数组,找到对应ID的项替换属性值,保持数组不可变性。 - 提交完成后重置输入框和编辑状态,回到初始状态。
内容的提问来源于stack exchange,提问作者Jonas
相关产品推荐
相关产品推荐

