我不确定为什么使用errorOption = key +'Error'然后使用[errorOption]设置状态时不会更新我的状态:true。因为我的formErrors状态使用与formDetails相同的初始键,但末尾带有“错误”,因此我将其串联起来。我也尝试过使用模板文字,但是在这里看级联看起来更容易。
我希望它验证表单以检查是否为空并将错误状态更改为true
const defaultData = {
username: '',
password: '',
}
const defaultErrorState = {
usernameError: false,
passwordError: false,
}
const [formDetails, setFormDetails] = useState(defaultData);
const [formErrors, setFormError] = useState(defaultErrorState);
const {
username,
password
} = formDetails
const {
usernameError,
passwordError
} = formErrors
const validateForm = (inputs) => {
const checkThreshold = (currentValue) => currentValue.length > 0;
let errorOption
Object.entries(inputs).forEach(([key, value]) => {
if (!checkThreshold(value)) {
errorOption = key + 'Error'
setFormError({
...formErrors,
[errorOption]: true
})
}
})
Object.entries(inputs).every(checkThreshold)
}
const handleSubmit = (event) => {
const basicInfoValues = {
username: username,
password: password,
}
if (validateForm(basicInfoValues)){
// login stuff
} else {alert("Fill in all fields")}
}