我有以下组件,它接受一个渲染props,它将值传递给子组件。 这是一个显示问题的代码沙盒。按提交并查看控制台。
这是组件:
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
在这里调用似乎并不理想,但是scrollToValidationError();
在初始useEffect
钩子中调用的调用是异步的,它需要在渲染函数之外。
我能做什么?