useState()react钩子总是返回初始状态的原因是什么



我正在react with validation中制作一个表单。我必须在验证后显示错误。所以我使用了useState()钩子,如下所示。但我似乎无法更新新状态,因为它总是返回初始值。我哪里错了?

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;

我尝试了console.log(error),但它总是返回initial statehi

这是因为状态更新是异步的。您需要在return之前console.log(error)才能在每次渲染时看到它。

在输入中,应该使用defaultValue而不是value

<input type='text'
placeholder='Eddard'
name='firstName'
defaultValue={firstName}
onChange={handleInputChange}
onBlur={handleBlur} />

如果您将日志移动到if语句中,也会更好

const validateFirstName = (name) => {
if (name.trim().length === 0) {
setError('Enter first Name');
console.log(error);
}
}

setState是异步的,如果需要捕获新值,可以使用useEffect。

最新更新