[英]What is the reason for useState() react hooks always returns the initial state?
I am making a form in react with validation.我正在制作一个与验证反应的表格。 I have to show the error after validation.
我必须在验证后显示错误。 So I used
useState()
hook as follows.所以我使用
useState()
钩子如下。 But it seems i can't update the new state as it always returns the initial value.但似乎我无法更新新的 state 因为它总是返回初始值。 Where did I go wrong?
我在哪里 go 错了?
import React, { useState } from 'react';
import './index.css';
const Firstname = ({ handleInputChange, firstName }) => {
const [error, setError] = useState('hi');
const handleBlur = (event) => {
const { value } = event.target;
validateFirstName(value);
}
const validateFirstName = (name) => {
if (name.trim().length === 0) {
setError('Enter first Name');
}
console.log(error);
}
return (
<>
<label>First Name</label>
<input type='text'
placeholder='Eddard'
name='firstName'
value={firstName}
onChange={handleInputChange}
onBlur={handleBlur} />
</>
)
}
export default Firstname;
I tried to console.log(error)
but it always returns the initial state
hi
.我试图
console.log(error)
但它总是返回initial state
hi
。
This is because state updates are asynchronous.这是因为 state 更新是异步的。 You need to
console.log(error)
just before your return
to see it at each render.您需要在
return
之前console.log(error)
才能在每次渲染时看到它。
In the input, you should use defaultValue
instead of value
在输入中,您应该使用
defaultValue
而不是value
<input type='text'
placeholder='Eddard'
name='firstName'
defaultValue={firstName}
onChange={handleInputChange}
onBlur={handleBlur} />
It would also be better if you move the log inside the if-statement如果将日志移动到 if 语句中也会更好
const validateFirstName = (name) => {
if (name.trim().length === 0) {
setError('Enter first Name');
console.log(error);
}
}
setState is asynchronous, if you need to catch the new value you can use useEffect. setState 是异步的,如果需要捕获新值可以使用 useEffect。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.