[英]Getting this error “Invalid hook call. Hooks can only be called inside of the body of a function component.” inside a react functional component?
[英]Call of hooks is inside of functional component give error Hooks can only be called inside of the body of a function component
我有用于翻译的组件语言
const Language = (props: IOwnProps) => {
// error is in next line for useSelector
const language = useSelector(
(state: IState) => state.currentLang
);
return getTranslations(
props.languageString
);
};
在表单中我使用 formik 进行验证
const validationSchema = () => {
const requiredFirstName = Language({
languageString: firstNameRequired,
});
return yup.object({
firstName: yup
.string()
.required(requiredFirstName)
});
};
这是表单组件
const UserForm = ({
userData: userData
setErrorIndex,
}: UserFormProps) => {
const formik = useFormik({
initialValues: {
userData: userData.firstName,
},
validationSchema,
onSubmit: (values) => {
const playerDataLocal = {
firstName: values.firstName,
};
handleSubmit(playerDataLocal);
},
});
return (
<form onSubmit={formik.handleSubmit}>
<TextField
id="firstName"
name="firstName"
label="First Name *"
defaultValue={formik.values.firstName}
onChange={formik.handleChange}
error={formik.touched.firstName && Boolean(formik.errors.firstName)}
helperText={formik.touched.firstName && formik.errors.firstName}
fullWidth
/>
</form>
);
};
export default UserForm;
在语言验证模式行中给出错误:无效的挂钩调用。 钩子只能在 function 组件的主体内部调用。
Language
调用来自validationSchema
,它是一个功能组件调用堆栈错误符合useSelector
来自validationSchema
的Language
调用在“useFormik”内部可能是这个问题吗? 有任何想法吗?
这是因为validationSchema
不是 React 组件。 您只能在功能组件内部使用钩子,并且由于validationSchema
返回的不是 JSX 或其他组件,因此它不被归类为 React 组件。
您可能希望将您的挂钩调用移动到UserForm
中,然后将结果作为参数传递给validationSchema
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.