4 回答
TA贡献1793条经验 获得超6个赞
setFormData({ ...formData, name: response.first_name });
setFormData({ ...formData, surname: response.last_name });
setFormData({ ...formData, email: response.email });
setFormData({ ...formData, password: response.id });
问题是,在下一次渲染之前不会改变。的值是上一次渲染上的值,它将保持这种状态,直到下一次渲染。因此,上面的每一行,设置旧数据,加上一个已更改的属性。然后,接下来的行使用不同的已更改属性设置旧数据,并且您在此之前更改的属性将丢失。formDataformData
您只想呼叫一次,并进行所需的所有更改。这样,在完成所有设置之前,您根本不需要更新。setFormDataformData
setFormData({
...formData,
name: response.first_name,
surname: response.last_name,
email: response.email,
password: response.id,
});
但是,看看你在这里的状态结构,你根本不需要前面的值,因为每个键都在响应中:
setFormData({
name: response.first_name,
surname: response.last_name,
email: response.email,
password: response.id,
});
TA贡献1830条经验 获得超9个赞
您应该使用以前的状态或仅调用一次。setFormData
// using previous state
// this solves your problem but isn't that good
// because you don't need to call it many times
const responseFacebook = (response) => {
setFormData(prev => ({ ...prev, name: response.first_name });
setFormData(prev => ({ ...prev, surname: response.last_name });
setFormData(prev => ({ ...prev, email: response.email });
setFormData(prev => ({ ...prev, password: response.id });
};
或
// calling only once
const responseFacebook = (response) => {
setFormData({
name: response.first_name,
surname: response.last_name,
email: response.email,
password: response.id
});
};
TA贡献2037条经验 获得超6个赞
使用usestate来设置状态,使用effect钩子来控制台更改,你的状态不会改变,因为它是一个异步任务,在钩子中没有回调函数在设置状态像class一样,所以使用useEffect
const responseFacebook = (response) => {
setFormData({
...formData,
name: response.first_name
surname: response.last_name,
email: response.email,
password: response.id
});
});
useEffect(() => {
console.log(formData.name);
console.log(formData.surname);
}, [formData]);
TA贡献1829条经验 获得超7个赞
useState Hooks 是异步的,您将无法立即看到反映的数据,而是使用 useEffect 查看结果
const responseFacebook = (response) => {
setFormData({ ...formData, name: response.first_name });
setFormData({ ...formData, surname: response.last_name });
setFormData({ ...formData, email: response.email });
setFormData({ ...formData, password: response.id });
console.log(formData.name); // This won't show the results
console.log(formData.surname); // This won't show the results
/* register({ name, surname, email, password }); */ // This won't show the results
};
useEffect(() => {
// action on update of formData
console.log(formData);
}, [formData]);
此外,您还可以进一步优化代码以:
setFormData({
...formData,
name: response.first_name,
surname: response.last_name,
email: response.email,
password: response.id
});
useEffect(() => {
// action on update of formData
console.log(formData);
}, [formData]);
添加回答
举报