在反应中添加和编辑来自同一表单的数据
Posted
技术标签:
【中文标题】在反应中添加和编辑来自同一表单的数据【英文标题】:Adding and Editing the data from the same form in react 【发布时间】:2021-11-25 10:32:31 【问题描述】:我是 react 新手,想知道如何通过应用条件从 react 表单中更新和编辑同一函数 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>
【问题讨论】:
【参考方案1】:我建议不要使用两种不同的状态,您可以只使用一种状态并执行类似的操作
const [formData, setFormData] = useState(
id: null
firstname: "",
lastname: "",
surname: "",
mailid: "",
company: "",
);
handleSubmit(formObject)
if(formData.id === null)
// if "id" is null its mean its a new record
//... create the unique ID here
else
// edit the existing record and update
【讨论】:
【参考方案2】:为了更新您的状态中的当前值,您应该根据您存储数据的方式使用数组或对象破坏。 如果您有对象数组
const [contacts, setContacts] = useState([
name: "John", age: 20,
name: "Dastn", age: 25
])
更新它(添加name: "Doe", age:30
)
const onSubmit = newObject =>
setContacts(prevState => [...prevState, newObject])
之后你的contacts
数组会变成这样:
[
name: "John", age: 20,
name: "Dastn", age: 25,
name: "Doe", age:30
]
【讨论】:
以上是关于在反应中添加和编辑来自同一表单的数据的主要内容,如果未能解决你的问题,请参考以下文章