0

我是新手,想知道如何通过应用条件从表单中更新和编辑同一函数 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>

4

2 回答 2

0

我建议不要使用两种不同的状态,而是只能使用一种状态并做类似的事情

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
  }

}

于 2021-10-05T06:38:17.577 回答
0

为了更新您所在州的当前值,您应该根据您存储数据的方式使用数组或对象破坏。如果您有对象数组

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}
]
于 2021-10-05T06:41:48.437 回答