我正在尝试通过useState React Hook更新表单
const [loginForm, setLoginForm] = useState({
username: {
value: "",
validation: {
required: true
},
valid: false,
touched: false,
},
password: {
value: "",
validation: {
required: true
},
valid: false,
touched: false,
}
})
我的输入元素正在使用onChange事件,该事件调用一个函数。根据for循环,此处的密钥是用户名或密码
<input className={classes.input_element} type="text" name="{key}" value={loginForm[key].value} onChange={event => inputChangedHandler(event, key)} required />
inputChangedHandler的定义如下:
const inputChangedHandler = (event, inputIdentifier) => {
event.preventDefault();
const updatedField = updateObject(loginForm[inputIdentifier], {value: event.target.value, touched: true, )})
const updatedForm = updateObject(loginForm, {[inputIdentifier]: updatedField,})
setLoginForm(updatedForm)
console.log(updatedForm)
console.log(loginForm)
}
在上面的代码中,在最后第三行中,我将使用updatedForm设置loginForm的实际值。但是,当我将updatedForm和loginForm记录到控制台时,两者都给出了不同的输出。
updatedForm
{username: {…}, password: {…}}
password: {value: "", validation: {…}, valid: false, touched: false}
username: {value: "a", validation: {…}, valid: true, touched: true}
__proto__: Object
loginForm
{username: {…}, password: {…}}
password: {value: "", validation: {…}, valid: false, touched: false}
username: {value: "", validation: {…}, valid: false, touched: false}
__proto__: Object
在输入字段中,我仅从loginForm中选择值,并且在那里获取了实际的更新值。为什么会这样?
答案 0 :(得分:1)
您需要具依赖关系的useEffect updateForm
useEffect(()=> {
//do what every you want when updatedForm changes
},[updatedForm])