简体   繁体   English

在反应中使用 api 数据编辑表单

[英]Edit form with api data in react

I have a form in react that is filled with data from an api.我有一个反应表格,里面填满了来自 api 的数据。 I want to edit this data in the form, but i can not do it, because api always overwrite the fields.我想在表单中编辑这些数据,但我做不到,因为 api 总是覆盖字段。

This is my code:这是我的代码:

let params = useParams();

const [student, setStudent] = useState([]);


useEffect(() => {
    API.getStudentDetails(params.studentId).then(setStudent);
},[student]);




function editStudent(){
    API.editStudent(student).then(result => {
        if (result){
            alert("Estudiante modificado");
        }
    })
}

return(
    <>
        <div>Editar alumno {student.dni}</div>
        <div>
            <form id="formulario">
                ID<input type='text' id='id' disabled value={student.id} /> <br />
                DNI<input type='text' id='dni' value={student.dni} onChange={event => setStudent({...student, dni:event.target.value})} /><br />
                Nombre<input type='text' id='nombre' value={student.nombre} onChange={event => setStudent({...student, nombre:event.target.value})} /><br />
                Dirección<input type='text' id='direccion' value={student.direccion} onChange={event => setStudent({...student, direccion:event.target.value})}/><br />
                Edad<input type='number' id='edad' value={student.edad} onChange={event => setStudent({...student, edad:event.target.value})}/><br />
                Email<input type='text' id='email' value={student.email} onChange={event => setStudent({...student, email:event.target.value})}/><br />
                
                
                <button id='editar' onClick={() => editStudent()}>Editar</button>
            </form>
        </div>
    </>
)

How can do this?怎么能做到这一点? Thanks in advance提前致谢

The problem is with your useEffect hook.问题在于您的useEffect挂钩。 The useEffect will be called every time the student state is changed.每次更改student useEffect时都会调用 useEffect。 You call setStudent on every form field changes which will trigger the useEffect which at the end will get the initial student data from the api.您在每个表单字段更改时调用setStudent ,这将触发useEffect ,最后将从 api 获取初始student数据。

What you can do is to remove the student from the useEffect array of dependencies.您可以做的是从useEffect依赖项数组中删除student

useEffect(() => {
    API.getStudentDetails(params.studentId).then(setStudent);
},[]);

With this, the useEffect will only be called when the component mount, or you can put params.studentId into the array if needed.这样, useEffect只会在组件挂载时被调用,或者如果需要,您可以将params.studentId放入数组中。

useEffect(() => {
    API.getStudentDetails(params.studentId).then(setStudent);
},[params.studentId]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM