【发布时间】:2022-08-02 18:40:37
【问题描述】:
我无法解决我遇到的问题基本上我提交表单并检查是否有空值。然后我将输入边框涂成红色或绿色。但是,我需要一直重新绘制边框,这意味着如果用户输入一个值,边框应该变成绿色(因此是 useEffect)。我这里有 2 个状态。一个跟踪验证错误索引(对于 value === \'\'),另一部分是 createForm 状态(表单字段)本身。 然后我通过道具发送索引。
注意:无限循环不是在初始渲染时发生,而是在表单以空值提交时发生。如果表单提交上没有空字段,则不会发生无限循环。
我愿意根据需要分享更多信息。
const [createForm, setCreateForm] = React.useState(() => createFormFields);
const [validationErrorIndexes, setValidationErrorIndexes] = React.useState([]);
//Function that is being triggered in useEffect - to recalculate validaiton error indexes and resets the indexes.
const validateFormFields = () => {
const newIndexes = [];
createForm.forEach((field, i) => {
if (!field.value) {
newIndexes.push(i);
}
})
setValidationErrorIndexes(newIndexes);
}
//(infinite loop occurs here).
React.useEffect(() => {
if (validationErrorIndexes.length) {
validateFormFields();
return;
}
}, [Object.values(createForm)]);
//Function form submit.
const handleCreateSubmit = (e) => {
e.preventDefault();
if (createForm.every(formField => Boolean(formField.value))) {
console.log(createForm)
// TODO: dispatch -> POST/createUser...
} else {
validateFormFields();
}
}
//I then pass down validationErrorIndexes via props and add error and success classes conditionally to paint the border.
{createForm && createForm.length && createForm.map((formEl, i) => {
if (formEl.type === \'select\') {
return (
<Select
className={`create-select ${(validationErrorIndexes.length && validationErrorIndexes.includes(i)) && \'error\'}`}
styles={customStyles}
placeholder={formEl.label}
key={i}
value={formEl.value}
onChange={(selectedOption) => handleOptionChange(selectedOption, i)}
options={formEl.options}
/>
)
}
return (
<CustomInput key={i} {...{ label: formEl.label, type: formEl.type, value: formEl.value, formState: createForm, formStateSetter: setCreateForm, i, validationErrorIndexes }} />
)
})}
标签: reactjs use-effect