为什么控制台记录对象时不显示其他两个对象属性?


import React, { useState } from 'react';
import axios from 'axios';
export default function Submit (props) {
const [data, setData] = useState({email: '', username: '', password: ''});
function handleChange(event) {
setData({[event.target.name]: event.target.value});
}   
function handleSubmit(e) {
e.preventDefault();
console.log(data);
let sentData = encodeURIComponent(data);
axios.post('http://localhost:3001/', sentData)
.then(response =>  {
console.log(response);
})
.catch(error => {
console.log(error);
});
}
return (
<div>
<form onSubmit = {handleSubmit} method = "post">
<input name = "email" placeholder = "enter your email" type = "text" value = {data.email} onChange = {handleChange}>
</input>
<input name = "username" placeholder = "enter your username" type = "text" value = {data.username} onChange = {handleChange}>
</input>
<input name = "password" placeholder = "enter your password" type = "password" value = {data.password} onChange = {handleChange}>
</input>
<div>
<button type = "submit">Submit</button>
</div>
</form>
</div>
);
}

我是个反应迟钝的新手。当我键入输入并单击提交时,handleSubmit上的console.log(data)只打印具有上次键入属性的对象。例如,假设我先键入密码,然后键入用户名,然后键入电子邮件,它会打印{email:'blabla'}并忽略密码,用户名?如何修改代码以打印整个对象?

因为您只返回最后更新的属性。

CODESANDBOX

假设在编辑username属性时,返回的对象仅具有username属性。它应该返回所有已经存在的属性,并且只更新username

setData((state) => ({ ...state, [event.target.name]: event.target.value }));

相关内容

  • 没有找到相关文章

最新更新