【发布时间】:2020-07-16 18:41:14
【问题描述】:
我有以下组件,它接受一个将值传递给子组件的渲染道具。 Here 是一个显示问题的代码框。按提交并查看控制台。
这是组件:
export const FormContainer = function FormContainer<V>({
initialValues,
validate,
render,
...rest
}: FormContainerProps<V>) {
const [hasValidationError, setHasValidationError] = useState(false);
const dispatch = useDispatch();
useEffect(() => {
if (!hasValidationError) {
return;
}
scrollToValidationError();
() => setHasValidationError(false);
}, [hasValidationError]);
return (
<>
<Formik
>
{({
isSubmitting,
submitCount,
isValid,
errors,
values,
}: FormikProps<V>) => {
const invalid = !isValid;
const submitted = submitCount > 0;
if (submitCount > 0 && invalid) {
setHasValidationError(true);
}
return (
<>
<Form>
<div className={styles.form}>
{render({
values,
errors,
isSubmitting,
invalid,
submitCount,
})}
</div>
</Form>
</>
);
}}
</Formik>
</>
);
};
如果存在验证错误,则调用 setHasValidationError,这会导致 react 出现此错误
Warning: Cannot update a component (`FormContainer`) while rendering a different component (`Formik`). To locate the bad setState() call inside `Formik`, follow the stack trace as described in
in Formik (created by FormContainer)
in FormContainer (created by Home)
in Home (created by Context.Consumer)
in Route (created by App)
in Switch (created by App)
in Router (created by App)
in App
我并不是说这个警告是错误的。在这里调用 setHasValidationError 似乎并不理想,但在初始 useEffect 钩子中调用的 scrollToValidationError(); 调用是异步的,它需要超出渲染函数。
我能做什么?
【问题讨论】:
-
我认为 hackape 是对的,反正是个 eslint 对吗? :P
标签: reactjs