我是新手,想知道如何通过应用条件从表单中更新和编辑同一函数 handleSubmit() 中的数组数据
这是我的代码
const Subcontentinfo = () => {
const [contacts, setContacts] = useState([
{ id: 1, firstname: "Mike", lastname: "Huston", surname: "MH", mailid: "mikehustoncorp@live.com", company: "Estra Boutique ltd." },
{ id: 2, firstname: "Richard", lastname: "", surname: "R", mailid: "mikehustoncorp@live.com", company: "Amazonia online" },
{ id: 3, firstname: "James", lastname: "Dustin", surname: "JD", mailid: "mikehustoncorp@live.com", company: "Alibaba Traders .co" },
{ id: 4, firstname: "Amanda", lastname: "Paul", surname: "AP", mailid: "mikehustoncorp@live.com", company: "Estra Boutique ltd." }
]);
const [addFormData, setAddFormData] = useState({
firstname: "",
lastname: "",
surname: "",
mailid: "",
company: "",
});
const [editContactId, setEditContactId] = useState(null);
const addData = () =>{
const newContact = {
id: contacts.length + 1,
firstname: addFormData.firstname,
lastname: addFormData.lastname,
mailid: addFormData.mailid,
company: addFormData.company
}
setAddFormData({
firstname: "",
lastname: "",
mailid: "",
company: "",
setContacts([...contacts, newContact]);
});
}
editData(){
const editedContact = {
id: editContactId,
firstname: addFormData.firstname,
lastname: addFormData.lastname,
mailid: addFormData.mailid,
company: addFormData.company,
};
const newContacts = [...contacts];
const index = contacts.findIndex((contact) => contact.id === editContactId);
newContacts[index] = editedContact;
setContacts(newContacts);
setEditContactId(null);
}
我希望 addData() 和 editData() 通过应用条件使用相同的方法(如handleSubmit())这是我的按钮:
<button type="submit" onClick={handleSubmit} className="data-saving" >Save</button>